code
stringlengths 501
4.91M
| package
stringlengths 2
88
| path
stringlengths 11
291
| filename
stringlengths 4
197
| parsed_code
stringlengths 0
4.91M
| quality_prob
float64 0
0.99
| learning_prob
float64 0.02
1
|
---|---|---|---|---|---|---|
from enum import Enum
from azure.core import CaseInsensitiveEnumMeta
class AcceptanceMode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The mode of acceptance for an agreement."""
CLICK_TO_ACCEPT = "ClickToAccept"
E_SIGN_EMBEDDED = "ESignEmbedded"
E_SIGN_OFFLINE = "ESignOffline"
class AccountStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current status of the billing account."""
ACTIVE = "Active"
DELETED = "Deleted"
DISABLED = "Disabled"
EXPIRED = "Expired"
TRANSFERRED = "Transferred"
EXTENDED = "Extended"
TERMINATED = "Terminated"
class AccountType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of customer."""
ENTERPRISE = "Enterprise"
INDIVIDUAL = "Individual"
PARTNER = "Partner"
class AddressValidationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Status of the address validation."""
VALID = "Valid"
INVALID = "Invalid"
class AgreementType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of agreement."""
MICROSOFT_CUSTOMER_AGREEMENT = "MicrosoftCustomerAgreement"
ENTERPRISE_AGREEMENT = "EnterpriseAgreement"
MICROSOFT_ONLINE_SERVICES_PROGRAM = "MicrosoftOnlineServicesProgram"
MICROSOFT_PARTNER_AGREEMENT = "MicrosoftPartnerAgreement"
class AutoRenew(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Indicates whether auto renewal is turned on or off for a product."""
OFF = "Off"
ON = "On"
class BillingFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The frequency at which the product will be billed."""
ONE_TIME = "OneTime"
MONTHLY = "Monthly"
USAGE_BASED = "UsageBased"
class BillingProfileSpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The billing profile spending limit."""
OFF = "Off"
ON = "On"
class BillingProfileStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The status of the billing profile."""
ACTIVE = "Active"
DISABLED = "Disabled"
WARNED = "Warned"
class BillingProfileStatusReasonCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Reason for the specified billing profile status."""
PAST_DUE = "PastDue"
SPENDING_LIMIT_REACHED = "SpendingLimitReached"
SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired"
class BillingRelationshipType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Identifies which services and purchases are paid by a billing profile."""
DIRECT = "Direct"
INDIRECT_CUSTOMER = "IndirectCustomer"
INDIRECT_PARTNER = "IndirectPartner"
CSP_PARTNER = "CSPPartner"
class BillingSubscriptionStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current billing status of the subscription."""
ACTIVE = "Active"
INACTIVE = "Inactive"
ABANDONED = "Abandoned"
DELETED = "Deleted"
WARNING = "Warning"
class Category(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The category of the agreement signed by a customer."""
MICROSOFT_CUSTOMER_AGREEMENT = "MicrosoftCustomerAgreement"
AFFILIATE_PURCHASE_TERMS = "AffiliatePurchaseTerms"
OTHER = "Other"
class DocumentSource(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The source of the document. ENF for Brazil and DRS for rest of the world."""
DRS = "DRS"
ENF = "ENF"
class DocumentType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of the document."""
INVOICE = "Invoice"
VOID_NOTE = "VoidNote"
TAX_RECEIPT = "TaxReceipt"
CREDIT_NOTE = "CreditNote"
class InvoiceDocumentType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of the document."""
INVOICE = "Invoice"
CREDIT_NOTE = "CreditNote"
class InvoiceSectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Identifies the state of an invoice section."""
ACTIVE = "Active"
RESTRICTED = "Restricted"
class InvoiceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current status of the invoice."""
DUE = "Due"
OVER_DUE = "OverDue"
PAID = "Paid"
VOID = "Void"
class InvoiceType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Invoice type."""
AZURE_SERVICE = "AzureService"
AZURE_MARKETPLACE = "AzureMarketplace"
AZURE_SUPPORT = "AzureSupport"
class MarketplacePurchasesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether Azure marketplace purchases are allowed for a billing profile."""
ALL_ALLOWED = "AllAllowed"
ONLY_FREE_ALLOWED = "OnlyFreeAllowed"
NOT_ALLOWED = "NotAllowed"
class PaymentMethodFamily(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The family of payment method."""
CREDITS = "Credits"
CHECK_WIRE = "CheckWire"
CREDIT_CARD = "CreditCard"
NONE = "None"
class ProductStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current status of the product."""
ACTIVE = "Active"
INACTIVE = "Inactive"
PAST_DUE = "PastDue"
EXPIRING = "Expiring"
EXPIRED = "Expired"
DISABLED = "Disabled"
CANCELLED = "Cancelled"
AUTO_RENEW = "AutoRenew"
class ProductTransferValidationErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Error code of the transfer validation response."""
INVALID_SOURCE = "InvalidSource"
PRODUCT_NOT_ACTIVE = "ProductNotActive"
INSUFFICIENT_PERMISSION_ON_SOURCE = "InsufficientPermissionOnSource"
INSUFFICIENT_PERMISSION_ON_DESTINATION = "InsufficientPermissionOnDestination"
DESTINATION_BILLING_PROFILE_PAST_DUE = "DestinationBillingProfilePastDue"
PRODUCT_TYPE_NOT_SUPPORTED = "ProductTypeNotSupported"
CROSS_BILLING_ACCOUNT_NOT_ALLOWED = "CrossBillingAccountNotAllowed"
NOT_AVAILABLE_FOR_DESTINATION_MARKET = "NotAvailableForDestinationMarket"
ONE_TIME_PURCHASE_PRODUCT_TRANSFER_NOT_ALLOWED = "OneTimePurchaseProductTransferNotAllowed"
class ReservationPurchasesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether Azure reservation purchases are allowed for a billing profile."""
ALLOWED = "Allowed"
NOT_ALLOWED = "NotAllowed"
class ReservationType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of transaction."""
PURCHASE = "Purchase"
USAGE_CHARGE = "Usage Charge"
class SpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The billing profile spending limit."""
OFF = "Off"
ON = "On"
class SpendingLimitForBillingProfile(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The billing profile spending limit."""
OFF = "Off"
ON = "On"
class StatusReasonCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Reason for the specified billing profile status."""
PAST_DUE = "PastDue"
SPENDING_LIMIT_REACHED = "SpendingLimitReached"
SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired"
class StatusReasonCodeForBillingProfile(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Reason for the specified billing profile status."""
PAST_DUE = "PastDue"
SPENDING_LIMIT_REACHED = "SpendingLimitReached"
SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired"
class SubscriptionTransferValidationErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Error code of the transfer validation response."""
BILLING_ACCOUNT_INACTIVE = "BillingAccountInactive"
CROSS_BILLING_ACCOUNT_NOT_ALLOWED = "CrossBillingAccountNotAllowed"
DESTINATION_BILLING_PROFILE_INACTIVE = "DestinationBillingProfileInactive"
DESTINATION_BILLING_PROFILE_NOT_FOUND = "DestinationBillingProfileNotFound"
DESTINATION_BILLING_PROFILE_PAST_DUE = "DestinationBillingProfilePastDue"
DESTINATION_INVOICE_SECTION_INACTIVE = "DestinationInvoiceSectionInactive"
DESTINATION_INVOICE_SECTION_NOT_FOUND = "DestinationInvoiceSectionNotFound"
INSUFFICIENT_PERMISSION_ON_DESTINATION = "InsufficientPermissionOnDestination"
INSUFFICIENT_PERMISSION_ON_SOURCE = "InsufficientPermissionOnSource"
INVALID_DESTINATION = "InvalidDestination"
INVALID_SOURCE = "InvalidSource"
MARKETPLACE_NOT_ENABLED_ON_DESTINATION = "MarketplaceNotEnabledOnDestination"
NOT_AVAILABLE_FOR_DESTINATION_MARKET = "NotAvailableForDestinationMarket"
PRODUCT_INACTIVE = "ProductInactive"
PRODUCT_NOT_FOUND = "ProductNotFound"
PRODUCT_TYPE_NOT_SUPPORTED = "ProductTypeNotSupported"
SOURCE_BILLING_PROFILE_PAST_DUE = "SourceBillingProfilePastDue"
SOURCE_INVOICE_SECTION_INACTIVE = "SourceInvoiceSectionInactive"
SUBSCRIPTION_NOT_ACTIVE = "SubscriptionNotActive"
SUBSCRIPTION_TYPE_NOT_SUPPORTED = "SubscriptionTypeNotSupported"
class TargetCloud(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Possible cloud environments."""
US_GOV = "USGov"
US_NAT = "USNat"
US_SEC = "USSec"
class TransactionTypeKind(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The kind of transaction. Options are all or reservation."""
ALL = "all"
RESERVATION = "reservation"
class ViewCharges(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether the users in customer's organization can view charges at
pay-as-you-go prices.
"""
ALLOWED = "Allowed"
NOT_ALLOWED = "NotAllowed"
class ViewChargesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether users with Azure RBAC access to a subscription can view its
charges.
"""
ALLOWED = "Allowed"
NOT_ALLOWED = "NotAllowed"
|
azure-mgmt-billing
|
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/models/_billing_management_client_enums.py
|
_billing_management_client_enums.py
|
from enum import Enum
from azure.core import CaseInsensitiveEnumMeta
class AcceptanceMode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The mode of acceptance for an agreement."""
CLICK_TO_ACCEPT = "ClickToAccept"
E_SIGN_EMBEDDED = "ESignEmbedded"
E_SIGN_OFFLINE = "ESignOffline"
class AccountStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current status of the billing account."""
ACTIVE = "Active"
DELETED = "Deleted"
DISABLED = "Disabled"
EXPIRED = "Expired"
TRANSFERRED = "Transferred"
EXTENDED = "Extended"
TERMINATED = "Terminated"
class AccountType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of customer."""
ENTERPRISE = "Enterprise"
INDIVIDUAL = "Individual"
PARTNER = "Partner"
class AddressValidationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Status of the address validation."""
VALID = "Valid"
INVALID = "Invalid"
class AgreementType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of agreement."""
MICROSOFT_CUSTOMER_AGREEMENT = "MicrosoftCustomerAgreement"
ENTERPRISE_AGREEMENT = "EnterpriseAgreement"
MICROSOFT_ONLINE_SERVICES_PROGRAM = "MicrosoftOnlineServicesProgram"
MICROSOFT_PARTNER_AGREEMENT = "MicrosoftPartnerAgreement"
class AutoRenew(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Indicates whether auto renewal is turned on or off for a product."""
OFF = "Off"
ON = "On"
class BillingFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The frequency at which the product will be billed."""
ONE_TIME = "OneTime"
MONTHLY = "Monthly"
USAGE_BASED = "UsageBased"
class BillingProfileSpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The billing profile spending limit."""
OFF = "Off"
ON = "On"
class BillingProfileStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The status of the billing profile."""
ACTIVE = "Active"
DISABLED = "Disabled"
WARNED = "Warned"
class BillingProfileStatusReasonCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Reason for the specified billing profile status."""
PAST_DUE = "PastDue"
SPENDING_LIMIT_REACHED = "SpendingLimitReached"
SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired"
class BillingRelationshipType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Identifies which services and purchases are paid by a billing profile."""
DIRECT = "Direct"
INDIRECT_CUSTOMER = "IndirectCustomer"
INDIRECT_PARTNER = "IndirectPartner"
CSP_PARTNER = "CSPPartner"
class BillingSubscriptionStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current billing status of the subscription."""
ACTIVE = "Active"
INACTIVE = "Inactive"
ABANDONED = "Abandoned"
DELETED = "Deleted"
WARNING = "Warning"
class Category(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The category of the agreement signed by a customer."""
MICROSOFT_CUSTOMER_AGREEMENT = "MicrosoftCustomerAgreement"
AFFILIATE_PURCHASE_TERMS = "AffiliatePurchaseTerms"
OTHER = "Other"
class DocumentSource(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The source of the document. ENF for Brazil and DRS for rest of the world."""
DRS = "DRS"
ENF = "ENF"
class DocumentType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of the document."""
INVOICE = "Invoice"
VOID_NOTE = "VoidNote"
TAX_RECEIPT = "TaxReceipt"
CREDIT_NOTE = "CreditNote"
class InvoiceDocumentType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of the document."""
INVOICE = "Invoice"
CREDIT_NOTE = "CreditNote"
class InvoiceSectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Identifies the state of an invoice section."""
ACTIVE = "Active"
RESTRICTED = "Restricted"
class InvoiceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current status of the invoice."""
DUE = "Due"
OVER_DUE = "OverDue"
PAID = "Paid"
VOID = "Void"
class InvoiceType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Invoice type."""
AZURE_SERVICE = "AzureService"
AZURE_MARKETPLACE = "AzureMarketplace"
AZURE_SUPPORT = "AzureSupport"
class MarketplacePurchasesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether Azure marketplace purchases are allowed for a billing profile."""
ALL_ALLOWED = "AllAllowed"
ONLY_FREE_ALLOWED = "OnlyFreeAllowed"
NOT_ALLOWED = "NotAllowed"
class PaymentMethodFamily(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The family of payment method."""
CREDITS = "Credits"
CHECK_WIRE = "CheckWire"
CREDIT_CARD = "CreditCard"
NONE = "None"
class ProductStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The current status of the product."""
ACTIVE = "Active"
INACTIVE = "Inactive"
PAST_DUE = "PastDue"
EXPIRING = "Expiring"
EXPIRED = "Expired"
DISABLED = "Disabled"
CANCELLED = "Cancelled"
AUTO_RENEW = "AutoRenew"
class ProductTransferValidationErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Error code of the transfer validation response."""
INVALID_SOURCE = "InvalidSource"
PRODUCT_NOT_ACTIVE = "ProductNotActive"
INSUFFICIENT_PERMISSION_ON_SOURCE = "InsufficientPermissionOnSource"
INSUFFICIENT_PERMISSION_ON_DESTINATION = "InsufficientPermissionOnDestination"
DESTINATION_BILLING_PROFILE_PAST_DUE = "DestinationBillingProfilePastDue"
PRODUCT_TYPE_NOT_SUPPORTED = "ProductTypeNotSupported"
CROSS_BILLING_ACCOUNT_NOT_ALLOWED = "CrossBillingAccountNotAllowed"
NOT_AVAILABLE_FOR_DESTINATION_MARKET = "NotAvailableForDestinationMarket"
ONE_TIME_PURCHASE_PRODUCT_TRANSFER_NOT_ALLOWED = "OneTimePurchaseProductTransferNotAllowed"
class ReservationPurchasesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether Azure reservation purchases are allowed for a billing profile."""
ALLOWED = "Allowed"
NOT_ALLOWED = "NotAllowed"
class ReservationType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of transaction."""
PURCHASE = "Purchase"
USAGE_CHARGE = "Usage Charge"
class SpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The billing profile spending limit."""
OFF = "Off"
ON = "On"
class SpendingLimitForBillingProfile(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The billing profile spending limit."""
OFF = "Off"
ON = "On"
class StatusReasonCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Reason for the specified billing profile status."""
PAST_DUE = "PastDue"
SPENDING_LIMIT_REACHED = "SpendingLimitReached"
SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired"
class StatusReasonCodeForBillingProfile(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Reason for the specified billing profile status."""
PAST_DUE = "PastDue"
SPENDING_LIMIT_REACHED = "SpendingLimitReached"
SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired"
class SubscriptionTransferValidationErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Error code of the transfer validation response."""
BILLING_ACCOUNT_INACTIVE = "BillingAccountInactive"
CROSS_BILLING_ACCOUNT_NOT_ALLOWED = "CrossBillingAccountNotAllowed"
DESTINATION_BILLING_PROFILE_INACTIVE = "DestinationBillingProfileInactive"
DESTINATION_BILLING_PROFILE_NOT_FOUND = "DestinationBillingProfileNotFound"
DESTINATION_BILLING_PROFILE_PAST_DUE = "DestinationBillingProfilePastDue"
DESTINATION_INVOICE_SECTION_INACTIVE = "DestinationInvoiceSectionInactive"
DESTINATION_INVOICE_SECTION_NOT_FOUND = "DestinationInvoiceSectionNotFound"
INSUFFICIENT_PERMISSION_ON_DESTINATION = "InsufficientPermissionOnDestination"
INSUFFICIENT_PERMISSION_ON_SOURCE = "InsufficientPermissionOnSource"
INVALID_DESTINATION = "InvalidDestination"
INVALID_SOURCE = "InvalidSource"
MARKETPLACE_NOT_ENABLED_ON_DESTINATION = "MarketplaceNotEnabledOnDestination"
NOT_AVAILABLE_FOR_DESTINATION_MARKET = "NotAvailableForDestinationMarket"
PRODUCT_INACTIVE = "ProductInactive"
PRODUCT_NOT_FOUND = "ProductNotFound"
PRODUCT_TYPE_NOT_SUPPORTED = "ProductTypeNotSupported"
SOURCE_BILLING_PROFILE_PAST_DUE = "SourceBillingProfilePastDue"
SOURCE_INVOICE_SECTION_INACTIVE = "SourceInvoiceSectionInactive"
SUBSCRIPTION_NOT_ACTIVE = "SubscriptionNotActive"
SUBSCRIPTION_TYPE_NOT_SUPPORTED = "SubscriptionTypeNotSupported"
class TargetCloud(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Possible cloud environments."""
US_GOV = "USGov"
US_NAT = "USNat"
US_SEC = "USSec"
class TransactionTypeKind(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The kind of transaction. Options are all or reservation."""
ALL = "all"
RESERVATION = "reservation"
class ViewCharges(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether the users in customer's organization can view charges at
pay-as-you-go prices.
"""
ALLOWED = "Allowed"
NOT_ALLOWED = "NotAllowed"
class ViewChargesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The policy that controls whether users with Azure RBAC access to a subscription can view its
charges.
"""
ALLOWED = "Allowed"
NOT_ALLOWED = "NotAllowed"
| 0.842313 | 0.115961 |
from ._models_py3 import AddressDetails
from ._models_py3 import Agreement
from ._models_py3 import AgreementListResult
from ._models_py3 import Amount
from ._models_py3 import AvailableBalance
from ._models_py3 import AzurePlan
from ._models_py3 import BillingAccount
from ._models_py3 import BillingAccountListResult
from ._models_py3 import BillingAccountUpdateRequest
from ._models_py3 import BillingPeriod
from ._models_py3 import BillingPeriodsListResult
from ._models_py3 import BillingPermissionsListResult
from ._models_py3 import BillingPermissionsProperties
from ._models_py3 import BillingProfile
from ._models_py3 import BillingProfileCreationRequest
from ._models_py3 import BillingProfileInfo
from ._models_py3 import BillingProfileListResult
from ._models_py3 import BillingProfilesOnExpand
from ._models_py3 import BillingProperty
from ._models_py3 import BillingRoleAssignment
from ._models_py3 import BillingRoleAssignmentListResult
from ._models_py3 import BillingRoleDefinition
from ._models_py3 import BillingRoleDefinitionListResult
from ._models_py3 import BillingSubscription
from ._models_py3 import BillingSubscriptionsListResult
from ._models_py3 import Customer
from ._models_py3 import CustomerListResult
from ._models_py3 import CustomerPolicy
from ._models_py3 import Department
from ._models_py3 import Document
from ._models_py3 import DownloadUrl
from ._models_py3 import Enrollment
from ._models_py3 import EnrollmentAccount
from ._models_py3 import EnrollmentAccountContext
from ._models_py3 import EnrollmentAccountListResult
from ._models_py3 import EnrollmentAccountSummary
from ._models_py3 import EnrollmentPolicies
from ._models_py3 import ErrorDetails
from ._models_py3 import ErrorResponse
from ._models_py3 import ErrorSubDetailsItem
from ._models_py3 import IndirectRelationshipInfo
from ._models_py3 import Instruction
from ._models_py3 import InstructionListResult
from ._models_py3 import Invoice
from ._models_py3 import InvoiceListResult
from ._models_py3 import InvoiceSection
from ._models_py3 import InvoiceSectionCreationRequest
from ._models_py3 import InvoiceSectionListResult
from ._models_py3 import InvoiceSectionListWithCreateSubPermissionResult
from ._models_py3 import InvoiceSectionWithCreateSubPermission
from ._models_py3 import InvoiceSectionsOnExpand
from ._models_py3 import Operation
from ._models_py3 import OperationDisplay
from ._models_py3 import OperationListResult
from ._models_py3 import OperationsErrorDetails
from ._models_py3 import OperationsErrorResponse
from ._models_py3 import Participants
from ._models_py3 import PaymentProperties
from ._models_py3 import Policy
from ._models_py3 import Product
from ._models_py3 import ProductsListResult
from ._models_py3 import RebillDetails
from ._models_py3 import Reseller
from ._models_py3 import Reservation
from ._models_py3 import ReservationPropertyUtilization
from ._models_py3 import ReservationSkuProperty
from ._models_py3 import ReservationSummary
from ._models_py3 import ReservationUtilizationAggregates
from ._models_py3 import ReservationsListResult
from ._models_py3 import Resource
from ._models_py3 import Transaction
from ._models_py3 import TransactionListResult
from ._models_py3 import TransferBillingSubscriptionRequestProperties
from ._models_py3 import TransferProductRequestProperties
from ._models_py3 import ValidateAddressResponse
from ._models_py3 import ValidateProductTransferEligibilityError
from ._models_py3 import ValidateProductTransferEligibilityResult
from ._models_py3 import ValidateSubscriptionTransferEligibilityError
from ._models_py3 import ValidateSubscriptionTransferEligibilityResult
from ._billing_management_client_enums import AcceptanceMode
from ._billing_management_client_enums import AccountStatus
from ._billing_management_client_enums import AccountType
from ._billing_management_client_enums import AddressValidationStatus
from ._billing_management_client_enums import AgreementType
from ._billing_management_client_enums import AutoRenew
from ._billing_management_client_enums import BillingFrequency
from ._billing_management_client_enums import BillingProfileSpendingLimit
from ._billing_management_client_enums import BillingProfileStatus
from ._billing_management_client_enums import BillingProfileStatusReasonCode
from ._billing_management_client_enums import BillingRelationshipType
from ._billing_management_client_enums import BillingSubscriptionStatusType
from ._billing_management_client_enums import Category
from ._billing_management_client_enums import DocumentSource
from ._billing_management_client_enums import DocumentType
from ._billing_management_client_enums import InvoiceDocumentType
from ._billing_management_client_enums import InvoiceSectionState
from ._billing_management_client_enums import InvoiceStatus
from ._billing_management_client_enums import InvoiceType
from ._billing_management_client_enums import MarketplacePurchasesPolicy
from ._billing_management_client_enums import PaymentMethodFamily
from ._billing_management_client_enums import ProductStatusType
from ._billing_management_client_enums import ProductTransferValidationErrorCode
from ._billing_management_client_enums import ReservationPurchasesPolicy
from ._billing_management_client_enums import ReservationType
from ._billing_management_client_enums import SpendingLimit
from ._billing_management_client_enums import SpendingLimitForBillingProfile
from ._billing_management_client_enums import StatusReasonCode
from ._billing_management_client_enums import StatusReasonCodeForBillingProfile
from ._billing_management_client_enums import SubscriptionTransferValidationErrorCode
from ._billing_management_client_enums import TargetCloud
from ._billing_management_client_enums import TransactionTypeKind
from ._billing_management_client_enums import ViewCharges
from ._billing_management_client_enums import ViewChargesPolicy
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"AddressDetails",
"Agreement",
"AgreementListResult",
"Amount",
"AvailableBalance",
"AzurePlan",
"BillingAccount",
"BillingAccountListResult",
"BillingAccountUpdateRequest",
"BillingPeriod",
"BillingPeriodsListResult",
"BillingPermissionsListResult",
"BillingPermissionsProperties",
"BillingProfile",
"BillingProfileCreationRequest",
"BillingProfileInfo",
"BillingProfileListResult",
"BillingProfilesOnExpand",
"BillingProperty",
"BillingRoleAssignment",
"BillingRoleAssignmentListResult",
"BillingRoleDefinition",
"BillingRoleDefinitionListResult",
"BillingSubscription",
"BillingSubscriptionsListResult",
"Customer",
"CustomerListResult",
"CustomerPolicy",
"Department",
"Document",
"DownloadUrl",
"Enrollment",
"EnrollmentAccount",
"EnrollmentAccountContext",
"EnrollmentAccountListResult",
"EnrollmentAccountSummary",
"EnrollmentPolicies",
"ErrorDetails",
"ErrorResponse",
"ErrorSubDetailsItem",
"IndirectRelationshipInfo",
"Instruction",
"InstructionListResult",
"Invoice",
"InvoiceListResult",
"InvoiceSection",
"InvoiceSectionCreationRequest",
"InvoiceSectionListResult",
"InvoiceSectionListWithCreateSubPermissionResult",
"InvoiceSectionWithCreateSubPermission",
"InvoiceSectionsOnExpand",
"Operation",
"OperationDisplay",
"OperationListResult",
"OperationsErrorDetails",
"OperationsErrorResponse",
"Participants",
"PaymentProperties",
"Policy",
"Product",
"ProductsListResult",
"RebillDetails",
"Reseller",
"Reservation",
"ReservationPropertyUtilization",
"ReservationSkuProperty",
"ReservationSummary",
"ReservationUtilizationAggregates",
"ReservationsListResult",
"Resource",
"Transaction",
"TransactionListResult",
"TransferBillingSubscriptionRequestProperties",
"TransferProductRequestProperties",
"ValidateAddressResponse",
"ValidateProductTransferEligibilityError",
"ValidateProductTransferEligibilityResult",
"ValidateSubscriptionTransferEligibilityError",
"ValidateSubscriptionTransferEligibilityResult",
"AcceptanceMode",
"AccountStatus",
"AccountType",
"AddressValidationStatus",
"AgreementType",
"AutoRenew",
"BillingFrequency",
"BillingProfileSpendingLimit",
"BillingProfileStatus",
"BillingProfileStatusReasonCode",
"BillingRelationshipType",
"BillingSubscriptionStatusType",
"Category",
"DocumentSource",
"DocumentType",
"InvoiceDocumentType",
"InvoiceSectionState",
"InvoiceStatus",
"InvoiceType",
"MarketplacePurchasesPolicy",
"PaymentMethodFamily",
"ProductStatusType",
"ProductTransferValidationErrorCode",
"ReservationPurchasesPolicy",
"ReservationType",
"SpendingLimit",
"SpendingLimitForBillingProfile",
"StatusReasonCode",
"StatusReasonCodeForBillingProfile",
"SubscriptionTransferValidationErrorCode",
"TargetCloud",
"TransactionTypeKind",
"ViewCharges",
"ViewChargesPolicy",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
|
azure-mgmt-billing
|
/azure_mgmt_billing-6.1.0b1-py3-none-any.whl/azure/mgmt/billing/models/__init__.py
|
__init__.py
|
from ._models_py3 import AddressDetails
from ._models_py3 import Agreement
from ._models_py3 import AgreementListResult
from ._models_py3 import Amount
from ._models_py3 import AvailableBalance
from ._models_py3 import AzurePlan
from ._models_py3 import BillingAccount
from ._models_py3 import BillingAccountListResult
from ._models_py3 import BillingAccountUpdateRequest
from ._models_py3 import BillingPeriod
from ._models_py3 import BillingPeriodsListResult
from ._models_py3 import BillingPermissionsListResult
from ._models_py3 import BillingPermissionsProperties
from ._models_py3 import BillingProfile
from ._models_py3 import BillingProfileCreationRequest
from ._models_py3 import BillingProfileInfo
from ._models_py3 import BillingProfileListResult
from ._models_py3 import BillingProfilesOnExpand
from ._models_py3 import BillingProperty
from ._models_py3 import BillingRoleAssignment
from ._models_py3 import BillingRoleAssignmentListResult
from ._models_py3 import BillingRoleDefinition
from ._models_py3 import BillingRoleDefinitionListResult
from ._models_py3 import BillingSubscription
from ._models_py3 import BillingSubscriptionsListResult
from ._models_py3 import Customer
from ._models_py3 import CustomerListResult
from ._models_py3 import CustomerPolicy
from ._models_py3 import Department
from ._models_py3 import Document
from ._models_py3 import DownloadUrl
from ._models_py3 import Enrollment
from ._models_py3 import EnrollmentAccount
from ._models_py3 import EnrollmentAccountContext
from ._models_py3 import EnrollmentAccountListResult
from ._models_py3 import EnrollmentAccountSummary
from ._models_py3 import EnrollmentPolicies
from ._models_py3 import ErrorDetails
from ._models_py3 import ErrorResponse
from ._models_py3 import ErrorSubDetailsItem
from ._models_py3 import IndirectRelationshipInfo
from ._models_py3 import Instruction
from ._models_py3 import InstructionListResult
from ._models_py3 import Invoice
from ._models_py3 import InvoiceListResult
from ._models_py3 import InvoiceSection
from ._models_py3 import InvoiceSectionCreationRequest
from ._models_py3 import InvoiceSectionListResult
from ._models_py3 import InvoiceSectionListWithCreateSubPermissionResult
from ._models_py3 import InvoiceSectionWithCreateSubPermission
from ._models_py3 import InvoiceSectionsOnExpand
from ._models_py3 import Operation
from ._models_py3 import OperationDisplay
from ._models_py3 import OperationListResult
from ._models_py3 import OperationsErrorDetails
from ._models_py3 import OperationsErrorResponse
from ._models_py3 import Participants
from ._models_py3 import PaymentProperties
from ._models_py3 import Policy
from ._models_py3 import Product
from ._models_py3 import ProductsListResult
from ._models_py3 import RebillDetails
from ._models_py3 import Reseller
from ._models_py3 import Reservation
from ._models_py3 import ReservationPropertyUtilization
from ._models_py3 import ReservationSkuProperty
from ._models_py3 import ReservationSummary
from ._models_py3 import ReservationUtilizationAggregates
from ._models_py3 import ReservationsListResult
from ._models_py3 import Resource
from ._models_py3 import Transaction
from ._models_py3 import TransactionListResult
from ._models_py3 import TransferBillingSubscriptionRequestProperties
from ._models_py3 import TransferProductRequestProperties
from ._models_py3 import ValidateAddressResponse
from ._models_py3 import ValidateProductTransferEligibilityError
from ._models_py3 import ValidateProductTransferEligibilityResult
from ._models_py3 import ValidateSubscriptionTransferEligibilityError
from ._models_py3 import ValidateSubscriptionTransferEligibilityResult
from ._billing_management_client_enums import AcceptanceMode
from ._billing_management_client_enums import AccountStatus
from ._billing_management_client_enums import AccountType
from ._billing_management_client_enums import AddressValidationStatus
from ._billing_management_client_enums import AgreementType
from ._billing_management_client_enums import AutoRenew
from ._billing_management_client_enums import BillingFrequency
from ._billing_management_client_enums import BillingProfileSpendingLimit
from ._billing_management_client_enums import BillingProfileStatus
from ._billing_management_client_enums import BillingProfileStatusReasonCode
from ._billing_management_client_enums import BillingRelationshipType
from ._billing_management_client_enums import BillingSubscriptionStatusType
from ._billing_management_client_enums import Category
from ._billing_management_client_enums import DocumentSource
from ._billing_management_client_enums import DocumentType
from ._billing_management_client_enums import InvoiceDocumentType
from ._billing_management_client_enums import InvoiceSectionState
from ._billing_management_client_enums import InvoiceStatus
from ._billing_management_client_enums import InvoiceType
from ._billing_management_client_enums import MarketplacePurchasesPolicy
from ._billing_management_client_enums import PaymentMethodFamily
from ._billing_management_client_enums import ProductStatusType
from ._billing_management_client_enums import ProductTransferValidationErrorCode
from ._billing_management_client_enums import ReservationPurchasesPolicy
from ._billing_management_client_enums import ReservationType
from ._billing_management_client_enums import SpendingLimit
from ._billing_management_client_enums import SpendingLimitForBillingProfile
from ._billing_management_client_enums import StatusReasonCode
from ._billing_management_client_enums import StatusReasonCodeForBillingProfile
from ._billing_management_client_enums import SubscriptionTransferValidationErrorCode
from ._billing_management_client_enums import TargetCloud
from ._billing_management_client_enums import TransactionTypeKind
from ._billing_management_client_enums import ViewCharges
from ._billing_management_client_enums import ViewChargesPolicy
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"AddressDetails",
"Agreement",
"AgreementListResult",
"Amount",
"AvailableBalance",
"AzurePlan",
"BillingAccount",
"BillingAccountListResult",
"BillingAccountUpdateRequest",
"BillingPeriod",
"BillingPeriodsListResult",
"BillingPermissionsListResult",
"BillingPermissionsProperties",
"BillingProfile",
"BillingProfileCreationRequest",
"BillingProfileInfo",
"BillingProfileListResult",
"BillingProfilesOnExpand",
"BillingProperty",
"BillingRoleAssignment",
"BillingRoleAssignmentListResult",
"BillingRoleDefinition",
"BillingRoleDefinitionListResult",
"BillingSubscription",
"BillingSubscriptionsListResult",
"Customer",
"CustomerListResult",
"CustomerPolicy",
"Department",
"Document",
"DownloadUrl",
"Enrollment",
"EnrollmentAccount",
"EnrollmentAccountContext",
"EnrollmentAccountListResult",
"EnrollmentAccountSummary",
"EnrollmentPolicies",
"ErrorDetails",
"ErrorResponse",
"ErrorSubDetailsItem",
"IndirectRelationshipInfo",
"Instruction",
"InstructionListResult",
"Invoice",
"InvoiceListResult",
"InvoiceSection",
"InvoiceSectionCreationRequest",
"InvoiceSectionListResult",
"InvoiceSectionListWithCreateSubPermissionResult",
"InvoiceSectionWithCreateSubPermission",
"InvoiceSectionsOnExpand",
"Operation",
"OperationDisplay",
"OperationListResult",
"OperationsErrorDetails",
"OperationsErrorResponse",
"Participants",
"PaymentProperties",
"Policy",
"Product",
"ProductsListResult",
"RebillDetails",
"Reseller",
"Reservation",
"ReservationPropertyUtilization",
"ReservationSkuProperty",
"ReservationSummary",
"ReservationUtilizationAggregates",
"ReservationsListResult",
"Resource",
"Transaction",
"TransactionListResult",
"TransferBillingSubscriptionRequestProperties",
"TransferProductRequestProperties",
"ValidateAddressResponse",
"ValidateProductTransferEligibilityError",
"ValidateProductTransferEligibilityResult",
"ValidateSubscriptionTransferEligibilityError",
"ValidateSubscriptionTransferEligibilityResult",
"AcceptanceMode",
"AccountStatus",
"AccountType",
"AddressValidationStatus",
"AgreementType",
"AutoRenew",
"BillingFrequency",
"BillingProfileSpendingLimit",
"BillingProfileStatus",
"BillingProfileStatusReasonCode",
"BillingRelationshipType",
"BillingSubscriptionStatusType",
"Category",
"DocumentSource",
"DocumentType",
"InvoiceDocumentType",
"InvoiceSectionState",
"InvoiceStatus",
"InvoiceType",
"MarketplacePurchasesPolicy",
"PaymentMethodFamily",
"ProductStatusType",
"ProductTransferValidationErrorCode",
"ReservationPurchasesPolicy",
"ReservationType",
"SpendingLimit",
"SpendingLimitForBillingProfile",
"StatusReasonCode",
"StatusReasonCodeForBillingProfile",
"SubscriptionTransferValidationErrorCode",
"TargetCloud",
"TransactionTypeKind",
"ViewCharges",
"ViewChargesPolicy",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
| 0.504883 | 0.078466 |
# Microsoft Azure SDK for Python
This is the Microsoft Azure Billingbenefits Management Client Library.
This package has been tested with Python 3.7+.
For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all).
## _Disclaimer_
_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_
# Usage
To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt)
For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/)
Code samples for this package can be found at [Billingbenefits Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com.
Additional code samples for different Azure services are available at [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples)
# Provide Feedback
If you encounter any bugs or have suggestions, please file an issue in the
[Issues](https://github.com/Azure/azure-sdk-for-python/issues)
section of the project.

|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/README.md
|
README.md
|
# Microsoft Azure SDK for Python
This is the Microsoft Azure Billingbenefits Management Client Library.
This package has been tested with Python 3.7+.
For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all).
## _Disclaimer_
_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_
# Usage
To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt)
For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/)
Code samples for this package can be found at [Billingbenefits Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com.
Additional code samples for different Azure services are available at [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples)
# Provide Feedback
If you encounter any bugs or have suggestions, please file an issue in the
[Issues](https://github.com/Azure/azure-sdk-for-python/issues)
section of the project.

| 0.773943 | 0.582818 |
import sys
from typing import Any, Optional, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
from ._version import VERSION
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class BillingBenefitsRPConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for BillingBenefitsRP.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "TokenCredential", expand: Optional[str] = None, **kwargs: Any) -> None:
super(BillingBenefitsRPConfiguration, self).__init__(**kwargs)
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", "2022-11-01")
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
self.credential = credential
self.expand = expand
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-billingbenefits/{}".format(VERSION))
self._configure(**kwargs)
def _configure(self, **kwargs: Any) -> None:
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = ARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/_configuration.py
|
_configuration.py
|
import sys
from typing import Any, Optional, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
from ._version import VERSION
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class BillingBenefitsRPConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for BillingBenefitsRP.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "TokenCredential", expand: Optional[str] = None, **kwargs: Any) -> None:
super(BillingBenefitsRPConfiguration, self).__init__(**kwargs)
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", "2022-11-01")
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
self.credential = credential
self.expand = expand
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-billingbenefits/{}".format(VERSION))
self._configure(**kwargs)
def _configure(self, **kwargs: Any) -> None:
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = ARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
| 0.610918 | 0.095687 |
from copy import deepcopy
from typing import Any, Optional, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from . import models as _models
from ._configuration import BillingBenefitsRPConfiguration
from ._serialization import Deserializer, Serializer
from .operations import (
BillingBenefitsRPOperationsMixin,
Operations,
ReservationOrderAliasOperations,
SavingsPlanOperations,
SavingsPlanOrderAliasOperations,
SavingsPlanOrderOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class BillingBenefitsRP(BillingBenefitsRPOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
"""Azure Benefits RP let users create and manage benefits like savings plan.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.billingbenefits.operations.Operations
:ivar savings_plan_order_alias: SavingsPlanOrderAliasOperations operations
:vartype savings_plan_order_alias:
azure.mgmt.billingbenefits.operations.SavingsPlanOrderAliasOperations
:ivar savings_plan_order: SavingsPlanOrderOperations operations
:vartype savings_plan_order: azure.mgmt.billingbenefits.operations.SavingsPlanOrderOperations
:ivar savings_plan: SavingsPlanOperations operations
:vartype savings_plan: azure.mgmt.billingbenefits.operations.SavingsPlanOperations
:ivar reservation_order_alias: ReservationOrderAliasOperations operations
:vartype reservation_order_alias:
azure.mgmt.billingbenefits.operations.ReservationOrderAliasOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
expand: Optional[str] = None,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = BillingBenefitsRPConfiguration(credential=credential, expand=expand, **kwargs)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.savings_plan_order_alias = SavingsPlanOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan_order = SavingsPlanOrderOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan = SavingsPlanOperations(self._client, self._config, self._serialize, self._deserialize)
self.reservation_order_alias = ReservationOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self) -> None:
self._client.close()
def __enter__(self) -> "BillingBenefitsRP":
self._client.__enter__()
return self
def __exit__(self, *exc_details) -> None:
self._client.__exit__(*exc_details)
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/_billing_benefits_rp.py
|
_billing_benefits_rp.py
|
from copy import deepcopy
from typing import Any, Optional, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from . import models as _models
from ._configuration import BillingBenefitsRPConfiguration
from ._serialization import Deserializer, Serializer
from .operations import (
BillingBenefitsRPOperationsMixin,
Operations,
ReservationOrderAliasOperations,
SavingsPlanOperations,
SavingsPlanOrderAliasOperations,
SavingsPlanOrderOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class BillingBenefitsRP(BillingBenefitsRPOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
"""Azure Benefits RP let users create and manage benefits like savings plan.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.billingbenefits.operations.Operations
:ivar savings_plan_order_alias: SavingsPlanOrderAliasOperations operations
:vartype savings_plan_order_alias:
azure.mgmt.billingbenefits.operations.SavingsPlanOrderAliasOperations
:ivar savings_plan_order: SavingsPlanOrderOperations operations
:vartype savings_plan_order: azure.mgmt.billingbenefits.operations.SavingsPlanOrderOperations
:ivar savings_plan: SavingsPlanOperations operations
:vartype savings_plan: azure.mgmt.billingbenefits.operations.SavingsPlanOperations
:ivar reservation_order_alias: ReservationOrderAliasOperations operations
:vartype reservation_order_alias:
azure.mgmt.billingbenefits.operations.ReservationOrderAliasOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
expand: Optional[str] = None,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = BillingBenefitsRPConfiguration(credential=credential, expand=expand, **kwargs)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.savings_plan_order_alias = SavingsPlanOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan_order = SavingsPlanOrderOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan = SavingsPlanOperations(self._client, self._config, self._serialize, self._deserialize)
self.reservation_order_alias = ReservationOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self) -> None:
self._client.close()
def __enter__(self) -> "BillingBenefitsRP":
self._client.__enter__()
return self
def __exit__(self, *exc_details) -> None:
self._client.__exit__(*exc_details)
| 0.849441 | 0.118487 |
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(savings_plan_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderAliasName": _SERIALIZER.url(
"savings_plan_order_alias_name", savings_plan_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(savings_plan_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderAliasName": _SERIALIZER.url(
"savings_plan_order_alias_name", savings_plan_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class SavingsPlanOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`savings_plan_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
def _create_initial(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> _models.SavingsPlanOrderAliasModel:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanOrderAliasModel")
request = build_create_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@overload
def begin_create(
self,
savings_plan_order_alias_name: str,
body: _models.SavingsPlanOrderAliasModel,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SavingsPlanOrderAliasModel or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self, savings_plan_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> LROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SavingsPlanOrderAliasModel or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> LROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SavingsPlanOrderAliasModel or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
polling: Union[bool, PollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = self._create_initial(
savings_plan_order_alias_name=savings_plan_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: PollingMethod = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
)
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@distributed_trace
def get(self, savings_plan_order_alias_name: str, **kwargs: Any) -> _models.SavingsPlanOrderAliasModel:
"""Get a savings plan.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderAliasModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/operations/_savings_plan_order_alias_operations.py
|
_savings_plan_order_alias_operations.py
|
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(savings_plan_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderAliasName": _SERIALIZER.url(
"savings_plan_order_alias_name", savings_plan_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(savings_plan_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderAliasName": _SERIALIZER.url(
"savings_plan_order_alias_name", savings_plan_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class SavingsPlanOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`savings_plan_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
def _create_initial(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> _models.SavingsPlanOrderAliasModel:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanOrderAliasModel")
request = build_create_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@overload
def begin_create(
self,
savings_plan_order_alias_name: str,
body: _models.SavingsPlanOrderAliasModel,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SavingsPlanOrderAliasModel or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self, savings_plan_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> LROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SavingsPlanOrderAliasModel or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> LROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SavingsPlanOrderAliasModel or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
polling: Union[bool, PollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = self._create_initial(
savings_plan_order_alias_name=savings_plan_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: PollingMethod = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
)
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@distributed_trace
def get(self, savings_plan_order_alias_name: str, **kwargs: Any) -> _models.SavingsPlanOrderAliasModel:
"""Get a savings plan.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderAliasModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"}
| 0.624179 | 0.08318 |
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(reservation_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"reservationOrderAliasName": _SERIALIZER.url(
"reservation_order_alias_name", reservation_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(reservation_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"reservationOrderAliasName": _SERIALIZER.url(
"reservation_order_alias_name", reservation_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class ReservationOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`reservation_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
def _create_initial(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> _models.ReservationOrderAliasResponse:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "ReservationOrderAliasRequest")
request = build_create_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@overload
def begin_create(
self,
reservation_order_alias_name: str,
body: _models.ReservationOrderAliasRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self, reservation_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> LROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> LROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
polling: Union[bool, PollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = self._create_initial(
reservation_order_alias_name=reservation_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: PollingMethod = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
)
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@distributed_trace
def get(self, reservation_order_alias_name: str, **kwargs: Any) -> _models.ReservationOrderAliasResponse:
"""Get a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ReservationOrderAliasResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
request = build_get_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/operations/_reservation_order_alias_operations.py
|
_reservation_order_alias_operations.py
|
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(reservation_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"reservationOrderAliasName": _SERIALIZER.url(
"reservation_order_alias_name", reservation_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(reservation_order_alias_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
) # pylint: disable=line-too-long
path_format_arguments = {
"reservationOrderAliasName": _SERIALIZER.url(
"reservation_order_alias_name", reservation_order_alias_name, "str", pattern=r"^[a-zA-Z0-9_\-\.]+$"
),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class ReservationOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`reservation_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
def _create_initial(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> _models.ReservationOrderAliasResponse:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "ReservationOrderAliasRequest")
request = build_create_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@overload
def begin_create(
self,
reservation_order_alias_name: str,
body: _models.ReservationOrderAliasRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self, reservation_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> LROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> LROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
polling: Union[bool, PollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = self._create_initial(
reservation_order_alias_name=reservation_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: PollingMethod = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
)
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@distributed_trace
def get(self, reservation_order_alias_name: str, **kwargs: Any) -> _models.ReservationOrderAliasResponse:
"""Get a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ReservationOrderAliasResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
request = build_get_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"}
| 0.625781 | 0.072308 |
import sys
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(savings_plan_order_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans"
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_all_request(
*,
filter: Optional[str] = None,
orderby: Optional[str] = None,
refresh_summary: Optional[str] = None,
skiptoken: Optional[float] = None,
selected_state: Optional[str] = None,
take: Optional[float] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/savingsPlans")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
if filter is not None:
_params["$filter"] = _SERIALIZER.query("filter", filter, "str")
if orderby is not None:
_params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str")
if refresh_summary is not None:
_params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str")
if skiptoken is not None:
_params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "float")
if selected_state is not None:
_params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str")
if take is not None:
_params["take"] = _SERIALIZER.query("take", take, "float")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
savings_plan_order_id: str, savings_plan_id: str, *, expand: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}",
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
"savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
if expand is not None:
_params["$expand"] = _SERIALIZER.query("expand", expand, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}",
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
"savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_update_request(savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/validate",
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
"savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class SavingsPlanOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`savings_plan` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, savings_plan_order_id: str, **kwargs: Any) -> Iterable["_models.SavingsPlanModel"]:
"""List savings plans in an order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans"}
@distributed_trace
def list_all(
self,
filter: Optional[str] = None,
orderby: Optional[str] = None,
refresh_summary: Optional[str] = None,
skiptoken: Optional[float] = None,
selected_state: Optional[str] = None,
take: Optional[float] = None,
**kwargs: Any
) -> Iterable["_models.SavingsPlanModel"]:
"""List savings plans.
:param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or',
and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation
properties include sku/name, properties/{appliedScopeType, archived, displayName,
displayProvisioningState, effectiveDateTime, expiryDate, provisioningState, quantity, renew,
reservedResourceType, term, userFriendlyAppliedScopeType, userFriendlyRenewState}. Default
value is None.
:type filter: str
:param orderby: May be used to sort order by reservation properties. Default value is None.
:type orderby: str
:param refresh_summary: To indicate whether to refresh the roll up counts of the savings plans
group by provisioning states. Default value is None.
:type refresh_summary: str
:param skiptoken: The number of savings plans to skip from the list before returning results.
Default value is None.
:type skiptoken: float
:param selected_state: The selected provisioning state. Default value is None.
:type selected_state: str
:param take: To number of savings plans to return. Default value is None.
:type take: float
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_all_request(
filter=filter,
orderby=orderby,
refresh_summary=refresh_summary,
skiptoken=skiptoken,
selected_state=selected_state,
take=take,
api_version=api_version,
template_url=self.list_all.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_all.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlans"}
@distributed_trace
def get(self, savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> _models.SavingsPlanModel:
"""Get savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateRequest, IO],
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
404: lambda response: ResourceNotFoundError(response=response, error_format=ARMErrorFormat),
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.SavingsPlanModel]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateRequest")
request = build_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if response.status_code == 202:
response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateValidateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateValidateRequest, IO],
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateValidateRequest")
request = build_validate_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/validate"
}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/operations/_savings_plan_operations.py
|
_savings_plan_operations.py
|
import sys
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(savings_plan_order_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans"
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_all_request(
*,
filter: Optional[str] = None,
orderby: Optional[str] = None,
refresh_summary: Optional[str] = None,
skiptoken: Optional[float] = None,
selected_state: Optional[str] = None,
take: Optional[float] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/savingsPlans")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
if filter is not None:
_params["$filter"] = _SERIALIZER.query("filter", filter, "str")
if orderby is not None:
_params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str")
if refresh_summary is not None:
_params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str")
if skiptoken is not None:
_params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "float")
if selected_state is not None:
_params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str")
if take is not None:
_params["take"] = _SERIALIZER.query("take", take, "float")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
savings_plan_order_id: str, savings_plan_id: str, *, expand: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}",
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
"savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
if expand is not None:
_params["$expand"] = _SERIALIZER.query("expand", expand, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}",
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
"savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_update_request(savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/validate",
) # pylint: disable=line-too-long
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
"savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class SavingsPlanOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`savings_plan` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, savings_plan_order_id: str, **kwargs: Any) -> Iterable["_models.SavingsPlanModel"]:
"""List savings plans in an order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans"}
@distributed_trace
def list_all(
self,
filter: Optional[str] = None,
orderby: Optional[str] = None,
refresh_summary: Optional[str] = None,
skiptoken: Optional[float] = None,
selected_state: Optional[str] = None,
take: Optional[float] = None,
**kwargs: Any
) -> Iterable["_models.SavingsPlanModel"]:
"""List savings plans.
:param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or',
and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation
properties include sku/name, properties/{appliedScopeType, archived, displayName,
displayProvisioningState, effectiveDateTime, expiryDate, provisioningState, quantity, renew,
reservedResourceType, term, userFriendlyAppliedScopeType, userFriendlyRenewState}. Default
value is None.
:type filter: str
:param orderby: May be used to sort order by reservation properties. Default value is None.
:type orderby: str
:param refresh_summary: To indicate whether to refresh the roll up counts of the savings plans
group by provisioning states. Default value is None.
:type refresh_summary: str
:param skiptoken: The number of savings plans to skip from the list before returning results.
Default value is None.
:type skiptoken: float
:param selected_state: The selected provisioning state. Default value is None.
:type selected_state: str
:param take: To number of savings plans to return. Default value is None.
:type take: float
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_all_request(
filter=filter,
orderby=orderby,
refresh_summary=refresh_summary,
skiptoken=skiptoken,
selected_state=selected_state,
take=take,
api_version=api_version,
template_url=self.list_all.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_all.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlans"}
@distributed_trace
def get(self, savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> _models.SavingsPlanModel:
"""Get savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateRequest, IO],
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
404: lambda response: ResourceNotFoundError(response=response, error_format=ARMErrorFormat),
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.SavingsPlanModel]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateRequest")
request = build_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if response.status_code == 202:
response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateValidateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateValidateRequest, IO],
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateValidateRequest")
request = build_validate_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/validate"
}
| 0.561696 | 0.077413 |
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_validate_purchase_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/validate")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class BillingBenefitsRPOperationsMixin(BillingBenefitsRPMixinABC):
@overload
def validate_purchase(
self, body: _models.SavingsPlanPurchaseValidateRequest, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_purchase(
self, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_purchase(
self, body: Union[_models.SavingsPlanPurchaseValidateRequest, IO], **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanPurchaseValidateRequest")
request = build_validate_purchase_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_purchase.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_purchase.metadata = {"url": "/providers/Microsoft.BillingBenefits/validate"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/operations/_billing_benefits_rp_operations.py
|
_billing_benefits_rp_operations.py
|
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_validate_purchase_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/validate")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class BillingBenefitsRPOperationsMixin(BillingBenefitsRPMixinABC):
@overload
def validate_purchase(
self, body: _models.SavingsPlanPurchaseValidateRequest, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_purchase(
self, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_purchase(
self, body: Union[_models.SavingsPlanPurchaseValidateRequest, IO], **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanPurchaseValidateRequest")
request = build_validate_purchase_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_purchase.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_purchase.metadata = {"url": "/providers/Microsoft.BillingBenefits/validate"}
| 0.666605 | 0.089296 |
import sys
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request(savings_plan_order_id: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}")
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
if expand is not None:
_params["$expand"] = _SERIALIZER.query("expand", expand, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_elevate_request(savings_plan_order_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/elevate"
)
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class SavingsPlanOrderOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`savings_plan_order` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def get(self, savings_plan_order_id: str, **kwargs: Any) -> _models.SavingsPlanOrderModel:
"""Get a savings plan order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}"}
@distributed_trace
def elevate(self, savings_plan_order_id: str, **kwargs: Any) -> _models.RoleAssignmentEntity:
"""Elevate as owner on savings plan order based on billing permissions.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RoleAssignmentEntity or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.RoleAssignmentEntity
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.RoleAssignmentEntity] = kwargs.pop("cls", None)
request = build_elevate_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.elevate.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RoleAssignmentEntity", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
elevate.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/elevate"}
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.SavingsPlanOrderModel"]:
"""List all Savings plan orders.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanOrderModel or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/operations/_savings_plan_order_operations.py
|
_savings_plan_order_operations.py
|
import sys
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request(savings_plan_order_id: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}")
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
if expand is not None:
_params["$expand"] = _SERIALIZER.query("expand", expand, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_elevate_request(savings_plan_order_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/elevate"
)
path_format_arguments = {
"savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/savingsPlanOrders")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class SavingsPlanOrderOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`savings_plan_order` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def get(self, savings_plan_order_id: str, **kwargs: Any) -> _models.SavingsPlanOrderModel:
"""Get a savings plan order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}"}
@distributed_trace
def elevate(self, savings_plan_order_id: str, **kwargs: Any) -> _models.RoleAssignmentEntity:
"""Elevate as owner on savings plan order based on billing permissions.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RoleAssignmentEntity or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.RoleAssignmentEntity
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.RoleAssignmentEntity] = kwargs.pop("cls", None)
request = build_elevate_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.elevate.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RoleAssignmentEntity", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
elevate.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/elevate"}
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.SavingsPlanOrderModel"]:
"""List all Savings plan orders.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanOrderModel or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders"}
| 0.621311 | 0.091261 |
import sys
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/operations")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.Operation"]:
"""Get operations.
List all the operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OperationListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/operations"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/operations/_operations.py
|
_operations.py
|
import sys
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import BillingBenefitsRPMixinABC, _convert_request
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01"))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.BillingBenefits/operations")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.BillingBenefitsRP`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.Operation"]:
"""Get operations.
List all the operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billingbenefits.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OperationListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/operations"}
| 0.624294 | 0.077134 |
import sys
from typing import Any, Optional, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class BillingBenefitsRPConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for BillingBenefitsRP.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "AsyncTokenCredential", expand: Optional[str] = None, **kwargs: Any) -> None:
super(BillingBenefitsRPConfiguration, self).__init__(**kwargs)
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", "2022-11-01")
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
self.credential = credential
self.expand = expand
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-billingbenefits/{}".format(VERSION))
self._configure(**kwargs)
def _configure(self, **kwargs: Any) -> None:
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/_configuration.py
|
_configuration.py
|
import sys
from typing import Any, Optional, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class BillingBenefitsRPConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for BillingBenefitsRP.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "AsyncTokenCredential", expand: Optional[str] = None, **kwargs: Any) -> None:
super(BillingBenefitsRPConfiguration, self).__init__(**kwargs)
api_version: Literal["2022-11-01"] = kwargs.pop("api_version", "2022-11-01")
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
self.credential = credential
self.expand = expand
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-billingbenefits/{}".format(VERSION))
self._configure(**kwargs)
def _configure(self, **kwargs: Any) -> None:
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
| 0.619011 | 0.097734 |
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from .. import models as _models
from .._serialization import Deserializer, Serializer
from ._configuration import BillingBenefitsRPConfiguration
from .operations import (
BillingBenefitsRPOperationsMixin,
Operations,
ReservationOrderAliasOperations,
SavingsPlanOperations,
SavingsPlanOrderAliasOperations,
SavingsPlanOrderOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class BillingBenefitsRP(BillingBenefitsRPOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
"""Azure Benefits RP let users create and manage benefits like savings plan.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.billingbenefits.aio.operations.Operations
:ivar savings_plan_order_alias: SavingsPlanOrderAliasOperations operations
:vartype savings_plan_order_alias:
azure.mgmt.billingbenefits.aio.operations.SavingsPlanOrderAliasOperations
:ivar savings_plan_order: SavingsPlanOrderOperations operations
:vartype savings_plan_order:
azure.mgmt.billingbenefits.aio.operations.SavingsPlanOrderOperations
:ivar savings_plan: SavingsPlanOperations operations
:vartype savings_plan: azure.mgmt.billingbenefits.aio.operations.SavingsPlanOperations
:ivar reservation_order_alias: ReservationOrderAliasOperations operations
:vartype reservation_order_alias:
azure.mgmt.billingbenefits.aio.operations.ReservationOrderAliasOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
expand: Optional[str] = None,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = BillingBenefitsRPConfiguration(credential=credential, expand=expand, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.savings_plan_order_alias = SavingsPlanOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan_order = SavingsPlanOrderOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan = SavingsPlanOperations(self._client, self._config, self._serialize, self._deserialize)
self.reservation_order_alias = ReservationOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "BillingBenefitsRP":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/_billing_benefits_rp.py
|
_billing_benefits_rp.py
|
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from .. import models as _models
from .._serialization import Deserializer, Serializer
from ._configuration import BillingBenefitsRPConfiguration
from .operations import (
BillingBenefitsRPOperationsMixin,
Operations,
ReservationOrderAliasOperations,
SavingsPlanOperations,
SavingsPlanOrderAliasOperations,
SavingsPlanOrderOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class BillingBenefitsRP(BillingBenefitsRPOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
"""Azure Benefits RP let users create and manage benefits like savings plan.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.billingbenefits.aio.operations.Operations
:ivar savings_plan_order_alias: SavingsPlanOrderAliasOperations operations
:vartype savings_plan_order_alias:
azure.mgmt.billingbenefits.aio.operations.SavingsPlanOrderAliasOperations
:ivar savings_plan_order: SavingsPlanOrderOperations operations
:vartype savings_plan_order:
azure.mgmt.billingbenefits.aio.operations.SavingsPlanOrderOperations
:ivar savings_plan: SavingsPlanOperations operations
:vartype savings_plan: azure.mgmt.billingbenefits.aio.operations.SavingsPlanOperations
:ivar reservation_order_alias: ReservationOrderAliasOperations operations
:vartype reservation_order_alias:
azure.mgmt.billingbenefits.aio.operations.ReservationOrderAliasOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param expand: May be used to expand the detail information of some properties. Default value
is None.
:type expand: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
expand: Optional[str] = None,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = BillingBenefitsRPConfiguration(credential=credential, expand=expand, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.savings_plan_order_alias = SavingsPlanOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan_order = SavingsPlanOrderOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.savings_plan = SavingsPlanOperations(self._client, self._config, self._serialize, self._deserialize)
self.reservation_order_alias = ReservationOrderAliasOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "BillingBenefitsRP":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
| 0.851521 | 0.123471 |
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._savings_plan_order_alias_operations import build_create_request, build_get_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SavingsPlanOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`savings_plan_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
async def _create_initial(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> _models.SavingsPlanOrderAliasModel:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanOrderAliasModel")
request = build_create_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@overload
async def begin_create(
self,
savings_plan_order_alias_name: str,
body: _models.SavingsPlanOrderAliasModel,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SavingsPlanOrderAliasModel or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self, savings_plan_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> AsyncLROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SavingsPlanOrderAliasModel or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> AsyncLROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SavingsPlanOrderAliasModel or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_initial(
savings_plan_order_alias_name=savings_plan_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@distributed_trace_async
async def get(self, savings_plan_order_alias_name: str, **kwargs: Any) -> _models.SavingsPlanOrderAliasModel:
"""Get a savings plan.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderAliasModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/operations/_savings_plan_order_alias_operations.py
|
_savings_plan_order_alias_operations.py
|
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._savings_plan_order_alias_operations import build_create_request, build_get_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SavingsPlanOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`savings_plan_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
async def _create_initial(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> _models.SavingsPlanOrderAliasModel:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanOrderAliasModel")
request = build_create_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@overload
async def begin_create(
self,
savings_plan_order_alias_name: str,
body: _models.SavingsPlanOrderAliasModel,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SavingsPlanOrderAliasModel or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self, savings_plan_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> AsyncLROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SavingsPlanOrderAliasModel or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self, savings_plan_order_alias_name: str, body: Union[_models.SavingsPlanOrderAliasModel, IO], **kwargs: Any
) -> AsyncLROPoller[_models.SavingsPlanOrderAliasModel]:
"""Create a savings plan. Learn more about permissions needed at
https://go.microsoft.com/fwlink/?linkid=2215851.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:param body: Request body for creating a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SavingsPlanOrderAliasModel or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_initial(
savings_plan_order_alias_name=savings_plan_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"
}
@distributed_trace_async
async def get(self, savings_plan_order_alias_name: str, **kwargs: Any) -> _models.SavingsPlanOrderAliasModel:
"""Get a savings plan.
:param savings_plan_order_alias_name: Name of the savings plan order alias. Required.
:type savings_plan_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderAliasModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderAliasModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_alias_name=savings_plan_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderAliasModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}"}
| 0.73782 | 0.087759 |
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._reservation_order_alias_operations import build_create_request, build_get_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ReservationOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`reservation_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
async def _create_initial(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> _models.ReservationOrderAliasResponse:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "ReservationOrderAliasRequest")
request = build_create_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@overload
async def begin_create(
self,
reservation_order_alias_name: str,
body: _models.ReservationOrderAliasRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self, reservation_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> AsyncLROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> AsyncLROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_initial(
reservation_order_alias_name=reservation_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@distributed_trace_async
async def get(self, reservation_order_alias_name: str, **kwargs: Any) -> _models.ReservationOrderAliasResponse:
"""Get a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ReservationOrderAliasResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
request = build_get_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/operations/_reservation_order_alias_operations.py
|
_reservation_order_alias_operations.py
|
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._reservation_order_alias_operations import build_create_request, build_get_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ReservationOrderAliasOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`reservation_order_alias` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
async def _create_initial(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> _models.ReservationOrderAliasResponse:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "ReservationOrderAliasRequest")
request = build_create_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if response.status_code == 201:
response_headers["Azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("Azure-AsyncOperation")
)
response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
return deserialized # type: ignore
_create_initial.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@overload
async def begin_create(
self,
reservation_order_alias_name: str,
body: _models.ReservationOrderAliasRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self, reservation_order_alias_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> AsyncLROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self, reservation_order_alias_name: str, body: Union[_models.ReservationOrderAliasRequest, IO], **kwargs: Any
) -> AsyncLROPoller[_models.ReservationOrderAliasResponse]:
"""Create a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:param body: Request body for creating a reservation order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ReservationOrderAliasResponse or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_initial(
reservation_order_alias_name=reservation_order_alias_name,
body=body,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create.metadata = {
"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"
}
@distributed_trace_async
async def get(self, reservation_order_alias_name: str, **kwargs: Any) -> _models.ReservationOrderAliasResponse:
"""Get a reservation order alias.
:param reservation_order_alias_name: Name of the reservation order alias. Required.
:type reservation_order_alias_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ReservationOrderAliasResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.ReservationOrderAliasResponse] = kwargs.pop("cls", None)
request = build_get_request(
reservation_order_alias_name=reservation_order_alias_name,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ReservationOrderAliasResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}"}
| 0.739611 | 0.080394 |
import sys
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._savings_plan_operations import (
build_get_request,
build_list_all_request,
build_list_request,
build_update_request,
build_validate_update_request,
)
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SavingsPlanOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`savings_plan` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, savings_plan_order_id: str, **kwargs: Any) -> AsyncIterable["_models.SavingsPlanModel"]:
"""List savings plans in an order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans"}
@distributed_trace
def list_all(
self,
filter: Optional[str] = None,
orderby: Optional[str] = None,
refresh_summary: Optional[str] = None,
skiptoken: Optional[float] = None,
selected_state: Optional[str] = None,
take: Optional[float] = None,
**kwargs: Any
) -> AsyncIterable["_models.SavingsPlanModel"]:
"""List savings plans.
:param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or',
and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation
properties include sku/name, properties/{appliedScopeType, archived, displayName,
displayProvisioningState, effectiveDateTime, expiryDate, provisioningState, quantity, renew,
reservedResourceType, term, userFriendlyAppliedScopeType, userFriendlyRenewState}. Default
value is None.
:type filter: str
:param orderby: May be used to sort order by reservation properties. Default value is None.
:type orderby: str
:param refresh_summary: To indicate whether to refresh the roll up counts of the savings plans
group by provisioning states. Default value is None.
:type refresh_summary: str
:param skiptoken: The number of savings plans to skip from the list before returning results.
Default value is None.
:type skiptoken: float
:param selected_state: The selected provisioning state. Default value is None.
:type selected_state: str
:param take: To number of savings plans to return. Default value is None.
:type take: float
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_all_request(
filter=filter,
orderby=orderby,
refresh_summary=refresh_summary,
skiptoken=skiptoken,
selected_state=selected_state,
take=take,
api_version=api_version,
template_url=self.list_all.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_all.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlans"}
@distributed_trace_async
async def get(self, savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> _models.SavingsPlanModel:
"""Get savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
async def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateRequest, IO],
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
404: lambda response: ResourceNotFoundError(response=response, error_format=ARMErrorFormat),
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.SavingsPlanModel]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateRequest")
request = build_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if response.status_code == 202:
response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
async def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateValidateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateValidateRequest, IO],
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateValidateRequest")
request = build_validate_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/validate"
}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/operations/_savings_plan_operations.py
|
_savings_plan_operations.py
|
import sys
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._savings_plan_operations import (
build_get_request,
build_list_all_request,
build_list_request,
build_update_request,
build_validate_update_request,
)
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SavingsPlanOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`savings_plan` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, savings_plan_order_id: str, **kwargs: Any) -> AsyncIterable["_models.SavingsPlanModel"]:
"""List savings plans in an order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans"}
@distributed_trace
def list_all(
self,
filter: Optional[str] = None,
orderby: Optional[str] = None,
refresh_summary: Optional[str] = None,
skiptoken: Optional[float] = None,
selected_state: Optional[str] = None,
take: Optional[float] = None,
**kwargs: Any
) -> AsyncIterable["_models.SavingsPlanModel"]:
"""List savings plans.
:param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or',
and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation
properties include sku/name, properties/{appliedScopeType, archived, displayName,
displayProvisioningState, effectiveDateTime, expiryDate, provisioningState, quantity, renew,
reservedResourceType, term, userFriendlyAppliedScopeType, userFriendlyRenewState}. Default
value is None.
:type filter: str
:param orderby: May be used to sort order by reservation properties. Default value is None.
:type orderby: str
:param refresh_summary: To indicate whether to refresh the roll up counts of the savings plans
group by provisioning states. Default value is None.
:type refresh_summary: str
:param skiptoken: The number of savings plans to skip from the list before returning results.
Default value is None.
:type skiptoken: float
:param selected_state: The selected provisioning state. Default value is None.
:type selected_state: str
:param take: To number of savings plans to return. Default value is None.
:type take: float
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanModel or the result of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModelListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_all_request(
filter=filter,
orderby=orderby,
refresh_summary=refresh_summary,
skiptoken=skiptoken,
selected_state=selected_state,
take=take,
api_version=api_version,
template_url=self.list_all.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanModelListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_all.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlans"}
@distributed_trace_async
async def get(self, savings_plan_order_id: str, savings_plan_id: str, **kwargs: Any) -> _models.SavingsPlanModel:
"""Get savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
async def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateRequest, IO],
**kwargs: Any
) -> Optional[_models.SavingsPlanModel]:
"""Update savings plan.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for patching a savings plan order alias. Is either a model type or a
IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanModel or None or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanModel or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
404: lambda response: ResourceNotFoundError(response=response, error_format=ARMErrorFormat),
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.SavingsPlanModel]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateRequest")
request = build_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("SavingsPlanModel", pipeline_response)
if response.status_code == 202:
response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}"
}
@overload
async def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: _models.SavingsPlanUpdateValidateRequest,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_update(
self,
savings_plan_order_id: str,
savings_plan_id: str,
body: Union[_models.SavingsPlanUpdateValidateRequest, IO],
**kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan patch.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:param savings_plan_id: ID of the savings plan. Required.
:type savings_plan_id: str
:param body: Request body for validating a savings plan patch request. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanUpdateValidateRequest")
request = build_validate_update_request(
savings_plan_order_id=savings_plan_order_id,
savings_plan_id=savings_plan_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_update.metadata = {
"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/validate"
}
| 0.737442 | 0.081264 |
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._billing_benefits_rp_operations import build_validate_purchase_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class BillingBenefitsRPOperationsMixin(BillingBenefitsRPMixinABC):
@overload
async def validate_purchase(
self, body: _models.SavingsPlanPurchaseValidateRequest, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_purchase(
self, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_purchase(
self, body: Union[_models.SavingsPlanPurchaseValidateRequest, IO], **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanPurchaseValidateRequest")
request = build_validate_purchase_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_purchase.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_purchase.metadata = {"url": "/providers/Microsoft.BillingBenefits/validate"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/operations/_billing_benefits_rp_operations.py
|
_billing_benefits_rp_operations.py
|
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._billing_benefits_rp_operations import build_validate_purchase_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class BillingBenefitsRPOperationsMixin(BillingBenefitsRPMixinABC):
@overload
async def validate_purchase(
self, body: _models.SavingsPlanPurchaseValidateRequest, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_purchase(
self, body: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Required.
:type body: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_purchase(
self, body: Union[_models.SavingsPlanPurchaseValidateRequest, IO], **kwargs: Any
) -> _models.SavingsPlanValidateResponse:
"""Validate savings plan purchase.
:param body: Request body for validating the purchase of a savings plan. Is either a model type
or a IO type. Required.
:type body: ~azure.mgmt.billingbenefits.models.SavingsPlanPurchaseValidateRequest or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanValidateResponse or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanValidateResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.SavingsPlanValidateResponse] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(body, (IO, bytes)):
_content = body
else:
_json = self._serialize.body(body, "SavingsPlanPurchaseValidateRequest")
request = build_validate_purchase_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_purchase.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanValidateResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_purchase.metadata = {"url": "/providers/Microsoft.BillingBenefits/validate"}
| 0.69181 | 0.089256 |
import sys
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._savings_plan_order_operations import build_elevate_request, build_get_request, build_list_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SavingsPlanOrderOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`savings_plan_order` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace_async
async def get(self, savings_plan_order_id: str, **kwargs: Any) -> _models.SavingsPlanOrderModel:
"""Get a savings plan order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}"}
@distributed_trace_async
async def elevate(self, savings_plan_order_id: str, **kwargs: Any) -> _models.RoleAssignmentEntity:
"""Elevate as owner on savings plan order based on billing permissions.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RoleAssignmentEntity or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.RoleAssignmentEntity
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.RoleAssignmentEntity] = kwargs.pop("cls", None)
request = build_elevate_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.elevate.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RoleAssignmentEntity", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
elevate.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/elevate"}
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.SavingsPlanOrderModel"]:
"""List all Savings plan orders.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanOrderModel or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/operations/_savings_plan_order_operations.py
|
_savings_plan_order_operations.py
|
import sys
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._savings_plan_order_operations import build_elevate_request, build_get_request, build_list_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SavingsPlanOrderOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`savings_plan_order` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace_async
async def get(self, savings_plan_order_id: str, **kwargs: Any) -> _models.SavingsPlanOrderModel:
"""Get a savings plan order.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SavingsPlanOrderModel or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModel] = kwargs.pop("cls", None)
request = build_get_request(
savings_plan_order_id=savings_plan_order_id,
expand=self._config.expand,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SavingsPlanOrderModel", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}"}
@distributed_trace_async
async def elevate(self, savings_plan_order_id: str, **kwargs: Any) -> _models.RoleAssignmentEntity:
"""Elevate as owner on savings plan order based on billing permissions.
:param savings_plan_order_id: Order ID of the savings plan. Required.
:type savings_plan_order_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RoleAssignmentEntity or the result of cls(response)
:rtype: ~azure.mgmt.billingbenefits.models.RoleAssignmentEntity
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.RoleAssignmentEntity] = kwargs.pop("cls", None)
request = build_elevate_request(
savings_plan_order_id=savings_plan_order_id,
api_version=api_version,
template_url=self.elevate.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RoleAssignmentEntity", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
elevate.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/elevate"}
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.SavingsPlanOrderModel"]:
"""List all Savings plan orders.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SavingsPlanOrderModel or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.SavingsPlanOrderModelList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SavingsPlanOrderModelList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders"}
| 0.672977 | 0.096408 |
import sys
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operations import build_list_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]:
"""Get operations.
List all the operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OperationListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/operations"}
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/aio/operations/_operations.py
|
_operations.py
|
import sys
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operations import build_list_request
from .._vendor import BillingBenefitsRPMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.billingbenefits.aio.BillingBenefitsRP`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]:
"""Get operations.
List all the operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billingbenefits.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-11-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OperationListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.BillingBenefits/operations"}
| 0.615666 | 0.086054 |
import datetime
from typing import List, Optional, TYPE_CHECKING, Union
from .. import _serialization
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from .. import models as _models
class AppliedScopeProperties(_serialization.Model):
"""Properties specific to applied scope type. Not required if not applicable.
:ivar tenant_id: Tenant ID where the benefit is applied.
:vartype tenant_id: str
:ivar management_group_id: Fully-qualified identifier of the management group where the benefit
must be applied.
:vartype management_group_id: str
:ivar subscription_id: Fully-qualified identifier of the subscription.
:vartype subscription_id: str
:ivar resource_group_id: Fully-qualified identifier of the resource group.
:vartype resource_group_id: str
:ivar display_name: Display name.
:vartype display_name: str
"""
_attribute_map = {
"tenant_id": {"key": "tenantId", "type": "str"},
"management_group_id": {"key": "managementGroupId", "type": "str"},
"subscription_id": {"key": "subscriptionId", "type": "str"},
"resource_group_id": {"key": "resourceGroupId", "type": "str"},
"display_name": {"key": "displayName", "type": "str"},
}
def __init__(
self,
*,
tenant_id: Optional[str] = None,
management_group_id: Optional[str] = None,
subscription_id: Optional[str] = None,
resource_group_id: Optional[str] = None,
display_name: Optional[str] = None,
**kwargs
):
"""
:keyword tenant_id: Tenant ID where the benefit is applied.
:paramtype tenant_id: str
:keyword management_group_id: Fully-qualified identifier of the management group where the
benefit must be applied.
:paramtype management_group_id: str
:keyword subscription_id: Fully-qualified identifier of the subscription.
:paramtype subscription_id: str
:keyword resource_group_id: Fully-qualified identifier of the resource group.
:paramtype resource_group_id: str
:keyword display_name: Display name.
:paramtype display_name: str
"""
super().__init__(**kwargs)
self.tenant_id = tenant_id
self.management_group_id = management_group_id
self.subscription_id = subscription_id
self.resource_group_id = resource_group_id
self.display_name = display_name
class BillingInformation(_serialization.Model):
"""billing information.
:ivar billing_currency_total_paid_amount:
:vartype billing_currency_total_paid_amount: ~azure.mgmt.billingbenefits.models.Price
:ivar billing_currency_prorated_amount:
:vartype billing_currency_prorated_amount: ~azure.mgmt.billingbenefits.models.Price
:ivar billing_currency_remaining_commitment_amount:
:vartype billing_currency_remaining_commitment_amount: ~azure.mgmt.billingbenefits.models.Price
"""
_attribute_map = {
"billing_currency_total_paid_amount": {"key": "billingCurrencyTotalPaidAmount", "type": "Price"},
"billing_currency_prorated_amount": {"key": "billingCurrencyProratedAmount", "type": "Price"},
"billing_currency_remaining_commitment_amount": {
"key": "billingCurrencyRemainingCommitmentAmount",
"type": "Price",
},
}
def __init__(
self,
*,
billing_currency_total_paid_amount: Optional["_models.Price"] = None,
billing_currency_prorated_amount: Optional["_models.Price"] = None,
billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None,
**kwargs
):
"""
:keyword billing_currency_total_paid_amount:
:paramtype billing_currency_total_paid_amount: ~azure.mgmt.billingbenefits.models.Price
:keyword billing_currency_prorated_amount:
:paramtype billing_currency_prorated_amount: ~azure.mgmt.billingbenefits.models.Price
:keyword billing_currency_remaining_commitment_amount:
:paramtype billing_currency_remaining_commitment_amount:
~azure.mgmt.billingbenefits.models.Price
"""
super().__init__(**kwargs)
self.billing_currency_total_paid_amount = billing_currency_total_paid_amount
self.billing_currency_prorated_amount = billing_currency_prorated_amount
self.billing_currency_remaining_commitment_amount = billing_currency_remaining_commitment_amount
class BillingPlanInformation(_serialization.Model):
"""Information describing the type of billing plan for this savings plan.
:ivar pricing_currency_total: Amount of money to be paid for the Order. Tax is not included.
:vartype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:ivar start_date: Date when the billing plan has started.
:vartype start_date: ~datetime.date
:ivar next_payment_due_date: For recurring billing plans, indicates the date when next payment
will be processed. Null when total is paid off.
:vartype next_payment_due_date: ~datetime.date
:ivar transactions:
:vartype transactions: list[~azure.mgmt.billingbenefits.models.PaymentDetail]
"""
_attribute_map = {
"pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"},
"start_date": {"key": "startDate", "type": "date"},
"next_payment_due_date": {"key": "nextPaymentDueDate", "type": "date"},
"transactions": {"key": "transactions", "type": "[PaymentDetail]"},
}
def __init__(
self,
*,
pricing_currency_total: Optional["_models.Price"] = None,
start_date: Optional[datetime.date] = None,
next_payment_due_date: Optional[datetime.date] = None,
transactions: Optional[List["_models.PaymentDetail"]] = None,
**kwargs
):
"""
:keyword pricing_currency_total: Amount of money to be paid for the Order. Tax is not included.
:paramtype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:keyword start_date: Date when the billing plan has started.
:paramtype start_date: ~datetime.date
:keyword next_payment_due_date: For recurring billing plans, indicates the date when next
payment will be processed. Null when total is paid off.
:paramtype next_payment_due_date: ~datetime.date
:keyword transactions:
:paramtype transactions: list[~azure.mgmt.billingbenefits.models.PaymentDetail]
"""
super().__init__(**kwargs)
self.pricing_currency_total = pricing_currency_total
self.start_date = start_date
self.next_payment_due_date = next_payment_due_date
self.transactions = transactions
class Price(_serialization.Model):
"""Price.
:ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase
record.
:vartype currency_code: str
:ivar amount:
:vartype amount: float
"""
_attribute_map = {
"currency_code": {"key": "currencyCode", "type": "str"},
"amount": {"key": "amount", "type": "float"},
}
def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs):
"""
:keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this
purchase record.
:paramtype currency_code: str
:keyword amount:
:paramtype amount: float
"""
super().__init__(**kwargs)
self.currency_code = currency_code
self.amount = amount
class Commitment(Price):
"""Commitment towards the benefit.
:ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase
record.
:vartype currency_code: str
:ivar amount:
:vartype amount: float
:ivar grain: Commitment grain. "Hourly"
:vartype grain: str or ~azure.mgmt.billingbenefits.models.CommitmentGrain
"""
_attribute_map = {
"currency_code": {"key": "currencyCode", "type": "str"},
"amount": {"key": "amount", "type": "float"},
"grain": {"key": "grain", "type": "str"},
}
def __init__(
self,
*,
currency_code: Optional[str] = None,
amount: Optional[float] = None,
grain: Optional[Union[str, "_models.CommitmentGrain"]] = None,
**kwargs
):
"""
:keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this
purchase record.
:paramtype currency_code: str
:keyword amount:
:paramtype amount: float
:keyword grain: Commitment grain. "Hourly"
:paramtype grain: str or ~azure.mgmt.billingbenefits.models.CommitmentGrain
"""
super().__init__(currency_code=currency_code, amount=amount, **kwargs)
self.grain = grain
class ErrorAdditionalInfo(_serialization.Model):
"""The resource management error additional info.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar type: The additional info type.
:vartype type: str
:ivar info: The additional info.
:vartype info: JSON
"""
_validation = {
"type": {"readonly": True},
"info": {"readonly": True},
}
_attribute_map = {
"type": {"key": "type", "type": "str"},
"info": {"key": "info", "type": "object"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.type = None
self.info = None
class ErrorDetail(_serialization.Model):
"""The error detail.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: The error code.
:vartype code: str
:ivar message: The error message.
:vartype message: str
:ivar target: The error target.
:vartype target: str
:ivar details: The error details.
:vartype details: list[~azure.mgmt.billingbenefits.models.ErrorDetail]
:ivar additional_info: The error additional info.
:vartype additional_info: list[~azure.mgmt.billingbenefits.models.ErrorAdditionalInfo]
"""
_validation = {
"code": {"readonly": True},
"message": {"readonly": True},
"target": {"readonly": True},
"details": {"readonly": True},
"additional_info": {"readonly": True},
}
_attribute_map = {
"code": {"key": "code", "type": "str"},
"message": {"key": "message", "type": "str"},
"target": {"key": "target", "type": "str"},
"details": {"key": "details", "type": "[ErrorDetail]"},
"additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.code = None
self.message = None
self.target = None
self.details = None
self.additional_info = None
class ErrorResponse(_serialization.Model):
"""Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.).
:ivar error: The error object.
:vartype error: ~azure.mgmt.billingbenefits.models.ErrorDetail
"""
_attribute_map = {
"error": {"key": "error", "type": "ErrorDetail"},
}
def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs):
"""
:keyword error: The error object.
:paramtype error: ~azure.mgmt.billingbenefits.models.ErrorDetail
"""
super().__init__(**kwargs)
self.error = error
class ExtendedStatusInfo(_serialization.Model):
"""ExtendedStatusInfo.
:ivar status_code: Status code providing additional information.
:vartype status_code: str
:ivar message: The message giving detailed information about the status code.
:vartype message: str
"""
_attribute_map = {
"status_code": {"key": "statusCode", "type": "str"},
"message": {"key": "message", "type": "str"},
}
def __init__(self, *, status_code: Optional[str] = None, message: Optional[str] = None, **kwargs):
"""
:keyword status_code: Status code providing additional information.
:paramtype status_code: str
:keyword message: The message giving detailed information about the status code.
:paramtype message: str
"""
super().__init__(**kwargs)
self.status_code = status_code
self.message = message
class Operation(_serialization.Model):
"""Details of a REST API operation, returned from the Resource Provider Operations API.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples:
"Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action".
:vartype name: str
:ivar is_data_action: Whether the operation applies to data-plane. This is "true" for
data-plane operations and "false" for ARM/control-plane operations.
:vartype is_data_action: bool
:ivar display: Localized display information for this particular operation.
:vartype display: ~azure.mgmt.billingbenefits.models.OperationDisplay
:ivar origin: The intended executor of the operation; as in Resource Based Access Control
(RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system",
and "user,system".
:vartype origin: str or ~azure.mgmt.billingbenefits.models.Origin
:ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for
internal only APIs. "Internal"
:vartype action_type: str or ~azure.mgmt.billingbenefits.models.ActionType
"""
_validation = {
"name": {"readonly": True},
"is_data_action": {"readonly": True},
"origin": {"readonly": True},
"action_type": {"readonly": True},
}
_attribute_map = {
"name": {"key": "name", "type": "str"},
"is_data_action": {"key": "isDataAction", "type": "bool"},
"display": {"key": "display", "type": "OperationDisplay"},
"origin": {"key": "origin", "type": "str"},
"action_type": {"key": "actionType", "type": "str"},
}
def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs):
"""
:keyword display: Localized display information for this particular operation.
:paramtype display: ~azure.mgmt.billingbenefits.models.OperationDisplay
"""
super().__init__(**kwargs)
self.name = None
self.is_data_action = None
self.display = display
self.origin = None
self.action_type = None
class OperationDisplay(_serialization.Model):
"""Localized display information for this particular operation.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft
Monitoring Insights" or "Microsoft Compute".
:vartype provider: str
:ivar resource: The localized friendly name of the resource type related to this operation.
E.g. "Virtual Machines" or "Job Schedule Collections".
:vartype resource: str
:ivar operation: The concise, localized friendly name for the operation; suitable for
dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine".
:vartype operation: str
:ivar description: The short, localized friendly description of the operation; suitable for
tool tips and detailed views.
:vartype description: str
"""
_validation = {
"provider": {"readonly": True},
"resource": {"readonly": True},
"operation": {"readonly": True},
"description": {"readonly": True},
}
_attribute_map = {
"provider": {"key": "provider", "type": "str"},
"resource": {"key": "resource", "type": "str"},
"operation": {"key": "operation", "type": "str"},
"description": {"key": "description", "type": "str"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.provider = None
self.resource = None
self.operation = None
self.description = None
class OperationListResult(_serialization.Model):
"""A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: List of operations supported by the resource provider.
:vartype value: list[~azure.mgmt.billingbenefits.models.Operation]
:ivar next_link: URL to get the next set of operation list results (if there are any).
:vartype next_link: str
"""
_validation = {
"value": {"readonly": True},
"next_link": {"readonly": True},
}
_attribute_map = {
"value": {"key": "value", "type": "[Operation]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.value = None
self.next_link = None
class OperationResultError(_serialization.Model):
"""Required if status == failed or status == canceled.
:ivar code: Required if status == failed or status == cancelled. If status == failed, provide
an invariant error code used for error troubleshooting, aggregation, and analysis.
:vartype code: str
:ivar message: Required if status == failed. Localized. If status == failed, provide an
actionable error message indicating what error occurred, and what the user can do to address
the issue.
:vartype message: str
"""
_attribute_map = {
"code": {"key": "code", "type": "str"},
"message": {"key": "message", "type": "str"},
}
def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs):
"""
:keyword code: Required if status == failed or status == cancelled. If status == failed,
provide an invariant error code used for error troubleshooting, aggregation, and analysis.
:paramtype code: str
:keyword message: Required if status == failed. Localized. If status == failed, provide an
actionable error message indicating what error occurred, and what the user can do to address
the issue.
:paramtype message: str
"""
super().__init__(**kwargs)
self.code = code
self.message = message
class PaymentDetail(_serialization.Model):
"""Information about payment related to a savings plan order.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar due_date: Date when the payment needs to be done.
:vartype due_date: ~datetime.date
:ivar payment_date: Date when the transaction is completed. Is null when it is scheduled.
:vartype payment_date: ~datetime.date
:ivar pricing_currency_total: Amount in pricing currency. Tax not included.
:vartype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:ivar billing_currency_total: Amount charged in Billing currency. Tax not included. Is null for
future payments.
:vartype billing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:ivar status: Describes whether the payment is completed, failed, cancelled or scheduled in the
future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled".
:vartype status: str or ~azure.mgmt.billingbenefits.models.PaymentStatus
:ivar extended_status_info:
:vartype extended_status_info: ~azure.mgmt.billingbenefits.models.ExtendedStatusInfo
:ivar billing_account: Billing account.
:vartype billing_account: str
"""
_validation = {
"extended_status_info": {"readonly": True},
}
_attribute_map = {
"due_date": {"key": "dueDate", "type": "date"},
"payment_date": {"key": "paymentDate", "type": "date"},
"pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"},
"billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"},
"status": {"key": "status", "type": "str"},
"extended_status_info": {"key": "extendedStatusInfo", "type": "ExtendedStatusInfo"},
"billing_account": {"key": "billingAccount", "type": "str"},
}
def __init__(
self,
*,
due_date: Optional[datetime.date] = None,
payment_date: Optional[datetime.date] = None,
pricing_currency_total: Optional["_models.Price"] = None,
billing_currency_total: Optional["_models.Price"] = None,
status: Optional[Union[str, "_models.PaymentStatus"]] = None,
billing_account: Optional[str] = None,
**kwargs
):
"""
:keyword due_date: Date when the payment needs to be done.
:paramtype due_date: ~datetime.date
:keyword payment_date: Date when the transaction is completed. Is null when it is scheduled.
:paramtype payment_date: ~datetime.date
:keyword pricing_currency_total: Amount in pricing currency. Tax not included.
:paramtype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:keyword billing_currency_total: Amount charged in Billing currency. Tax not included. Is null
for future payments.
:paramtype billing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:keyword status: Describes whether the payment is completed, failed, cancelled or scheduled in
the future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled".
:paramtype status: str or ~azure.mgmt.billingbenefits.models.PaymentStatus
:keyword billing_account: Billing account.
:paramtype billing_account: str
"""
super().__init__(**kwargs)
self.due_date = due_date
self.payment_date = payment_date
self.pricing_currency_total = pricing_currency_total
self.billing_currency_total = billing_currency_total
self.status = status
self.extended_status_info = None
self.billing_account = billing_account
class PricingCurrencyTotal(Price):
"""PricingCurrencyTotal.
:ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase
record.
:vartype currency_code: str
:ivar amount:
:vartype amount: float
:ivar duration: Represents either billing plan or savings plan term in ISO 8601 format. Known
values are: "P1M", "P1Y", and "P3Y".
:vartype duration: str or ~azure.mgmt.billingbenefits.models.PricingCurrencyDuration
"""
_attribute_map = {
"currency_code": {"key": "currencyCode", "type": "str"},
"amount": {"key": "amount", "type": "float"},
"duration": {"key": "duration", "type": "str"},
}
def __init__(
self,
*,
currency_code: Optional[str] = None,
amount: Optional[float] = None,
duration: Optional[Union[str, "_models.PricingCurrencyDuration"]] = None,
**kwargs
):
"""
:keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this
purchase record.
:paramtype currency_code: str
:keyword amount:
:paramtype amount: float
:keyword duration: Represents either billing plan or savings plan term in ISO 8601 format.
Known values are: "P1M", "P1Y", and "P3Y".
:paramtype duration: str or ~azure.mgmt.billingbenefits.models.PricingCurrencyDuration
"""
super().__init__(currency_code=currency_code, amount=amount, **kwargs)
self.duration = duration
class PurchaseRequest(_serialization.Model):
"""PurchaseRequest.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar sku: The SKU to be applied for this resource.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar display_name: Friendly name of the savings plan.
:vartype display_name: str
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar commitment: Commitment towards the benefit.
:vartype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:ivar effective_date_time: DateTime of the savings plan starts providing benefit from.
:vartype effective_date_time: ~datetime.datetime
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
"""
_validation = {
"effective_date_time": {"readonly": True},
}
_attribute_map = {
"sku": {"key": "sku", "type": "Sku"},
"display_name": {"key": "properties.displayName", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"commitment": {"key": "properties.commitment", "type": "Commitment"},
"effective_date_time": {"key": "properties.effectiveDateTime", "type": "iso-8601"},
"renew": {"key": "properties.renew", "type": "bool"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
}
def __init__(
self,
*,
sku: Optional["_models.Sku"] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
commitment: Optional["_models.Commitment"] = None,
renew: bool = False,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
**kwargs
):
"""
:keyword sku: The SKU to be applied for this resource.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword display_name: Friendly name of the savings plan.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword commitment: Commitment towards the benefit.
:paramtype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.display_name = display_name
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.commitment = commitment
self.effective_date_time = None
self.renew = renew
self.applied_scope_properties = applied_scope_properties
class RenewProperties(_serialization.Model):
"""RenewProperties.
:ivar purchase_properties:
:vartype purchase_properties: ~azure.mgmt.billingbenefits.models.PurchaseRequest
"""
_attribute_map = {
"purchase_properties": {"key": "purchaseProperties", "type": "PurchaseRequest"},
}
def __init__(self, *, purchase_properties: Optional["_models.PurchaseRequest"] = None, **kwargs):
"""
:keyword purchase_properties:
:paramtype purchase_properties: ~azure.mgmt.billingbenefits.models.PurchaseRequest
"""
super().__init__(**kwargs)
self.purchase_properties = purchase_properties
class Resource(_serialization.Model):
"""Common fields that are returned in the response for all Azure Resource Manager resources.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.id = None
self.name = None
self.type = None
self.system_data = None
class ReservationOrderAliasRequest(Resource): # pylint: disable=too-many-instance-attributes
"""Reservation order alias.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Reservation order SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar location: The Azure Region where the reservation benefits are applied to.
:vartype location: str
:ivar display_name: Display name.
:vartype display_name: str
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar quantity: Total Quantity of the SKUs purchased in the Reservation.
:vartype quantity: int
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:vartype reserved_resource_type: str or ~azure.mgmt.billingbenefits.models.ReservedResourceType
:ivar review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be
reviewed.
:vartype review_date_time: ~datetime.datetime
:ivar reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:vartype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequestPropertiesReservedResourceProperties
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"quantity": {"minimum": 1},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"location": {"key": "location", "type": "str"},
"display_name": {"key": "properties.displayName", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"quantity": {"key": "properties.quantity", "type": "int"},
"renew": {"key": "properties.renew", "type": "bool"},
"reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"},
"review_date_time": {"key": "properties.reviewDateTime", "type": "iso-8601"},
"reserved_resource_properties": {
"key": "properties.reservedResourceProperties",
"type": "ReservationOrderAliasRequestPropertiesReservedResourceProperties",
},
}
def __init__(
self,
*,
sku: "_models.Sku",
location: Optional[str] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
quantity: Optional[int] = None,
renew: bool = False,
reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None,
review_date_time: Optional[datetime.datetime] = None,
reserved_resource_properties: Optional[
"_models.ReservationOrderAliasRequestPropertiesReservedResourceProperties"
] = None,
**kwargs
):
"""
:keyword sku: Reservation order SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword location: The Azure Region where the reservation benefits are applied to.
:paramtype location: str
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword quantity: Total Quantity of the SKUs purchased in the Reservation.
:paramtype quantity: int
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:paramtype reserved_resource_type: str or
~azure.mgmt.billingbenefits.models.ReservedResourceType
:keyword review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be
reviewed.
:paramtype review_date_time: ~datetime.datetime
:keyword reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:paramtype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequestPropertiesReservedResourceProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.location = location
self.display_name = display_name
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.quantity = quantity
self.renew = renew
self.reserved_resource_type = reserved_resource_type
self.review_date_time = review_date_time
self.reserved_resource_properties = reserved_resource_properties
class ReservationOrderAliasRequestPropertiesReservedResourceProperties(_serialization.Model):
"""Properties specific to each reserved resource type. Not required if not applicable.
:ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in
the same VM size group. Known values are: "On" and "Off".
:vartype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
_attribute_map = {
"instance_flexibility": {"key": "instanceFlexibility", "type": "str"},
}
def __init__(self, *, instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, **kwargs):
"""
:keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs
in the same VM size group. Known values are: "On" and "Off".
:paramtype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
super().__init__(**kwargs)
self.instance_flexibility = instance_flexibility
class ReservationOrderAliasResponse(Resource): # pylint: disable=too-many-instance-attributes
"""Reservation order alias.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Reservation order SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar location: The Azure Region where the reserved resource lives.
:vartype location: str
:ivar display_name: Display name.
:vartype display_name: str
:ivar reservation_order_id: Identifier of the reservation order created.
:vartype reservation_order_id: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar quantity: Total Quantity of the SKUs purchased in the Reservation.
:vartype quantity: int
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:vartype reserved_resource_type: str or ~azure.mgmt.billingbenefits.models.ReservedResourceType
:ivar review_date_time: This is the date-time when the Reservation needs to be reviewed.
:vartype review_date_time: ~datetime.datetime
:ivar reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:vartype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponsePropertiesReservedResourceProperties
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"reservation_order_id": {"readonly": True},
"provisioning_state": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"location": {"key": "location", "type": "str"},
"display_name": {"key": "properties.displayName", "type": "str"},
"reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"quantity": {"key": "properties.quantity", "type": "int"},
"renew": {"key": "properties.renew", "type": "bool"},
"reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"},
"review_date_time": {"key": "properties.reviewDateTime", "type": "iso-8601"},
"reserved_resource_properties": {
"key": "properties.reservedResourceProperties",
"type": "ReservationOrderAliasResponsePropertiesReservedResourceProperties",
},
}
def __init__(
self,
*,
sku: "_models.Sku",
location: Optional[str] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
quantity: Optional[int] = None,
renew: bool = False,
reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None,
review_date_time: Optional[datetime.datetime] = None,
reserved_resource_properties: Optional[
"_models.ReservationOrderAliasResponsePropertiesReservedResourceProperties"
] = None,
**kwargs
):
"""
:keyword sku: Reservation order SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword location: The Azure Region where the reserved resource lives.
:paramtype location: str
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword quantity: Total Quantity of the SKUs purchased in the Reservation.
:paramtype quantity: int
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:paramtype reserved_resource_type: str or
~azure.mgmt.billingbenefits.models.ReservedResourceType
:keyword review_date_time: This is the date-time when the Reservation needs to be reviewed.
:paramtype review_date_time: ~datetime.datetime
:keyword reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:paramtype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponsePropertiesReservedResourceProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.location = location
self.display_name = display_name
self.reservation_order_id = None
self.provisioning_state = None
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.quantity = quantity
self.renew = renew
self.reserved_resource_type = reserved_resource_type
self.review_date_time = review_date_time
self.reserved_resource_properties = reserved_resource_properties
class ReservationOrderAliasResponsePropertiesReservedResourceProperties(_serialization.Model):
"""Properties specific to each reserved resource type. Not required if not applicable.
:ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in
the same VM size group. Known values are: "On" and "Off".
:vartype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
_attribute_map = {
"instance_flexibility": {"key": "instanceFlexibility", "type": "str"},
}
def __init__(self, *, instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, **kwargs):
"""
:keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs
in the same VM size group. Known values are: "On" and "Off".
:paramtype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
super().__init__(**kwargs)
self.instance_flexibility = instance_flexibility
class RoleAssignmentEntity(_serialization.Model):
"""Role assignment entity.
:ivar id: Role assignment entity id.
:vartype id: str
:ivar name: Role assignment entity name.
:vartype name: str
:ivar principal_id: Principal Id.
:vartype principal_id: str
:ivar role_definition_id: Role definition id.
:vartype role_definition_id: str
:ivar scope: Scope of the role assignment entity.
:vartype scope: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"principal_id": {"key": "properties.principalId", "type": "str"},
"role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"},
"scope": {"key": "properties.scope", "type": "str"},
}
def __init__(
self,
*,
id: Optional[str] = None, # pylint: disable=redefined-builtin
name: Optional[str] = None,
principal_id: Optional[str] = None,
role_definition_id: Optional[str] = None,
scope: Optional[str] = None,
**kwargs
):
"""
:keyword id: Role assignment entity id.
:paramtype id: str
:keyword name: Role assignment entity name.
:paramtype name: str
:keyword principal_id: Principal Id.
:paramtype principal_id: str
:keyword role_definition_id: Role definition id.
:paramtype role_definition_id: str
:keyword scope: Scope of the role assignment entity.
:paramtype scope: str
"""
super().__init__(**kwargs)
self.id = id
self.name = name
self.principal_id = principal_id
self.role_definition_id = role_definition_id
self.scope = scope
class SavingsPlanModel(Resource): # pylint: disable=too-many-instance-attributes
"""Savings plan.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Savings plan SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar display_name: Display name.
:vartype display_name: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar display_provisioning_state: The provisioning state of the savings plan for display, e.g.
Succeeded.
:vartype display_provisioning_state: str
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar billing_profile_id: Fully-qualified identifier of the billing profile where the savings
plan is applied. Present only for Field-led or Customer-led customers.
:vartype billing_profile_id: str
:ivar customer_id: Fully-qualified identifier of the customer where the savings plan is
applied. Present only for Partner-led customers.
:vartype customer_id: str
:ivar billing_account_id: Fully-qualified identifier of the billing account where the savings
plan is applied. Present only for Enterprise Agreement customers.
:vartype billing_account_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar user_friendly_applied_scope_type: The applied scope type of the savings plan for display,
e.g. Shared.
:vartype user_friendly_applied_scope_type: str
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar commitment: Commitment towards the benefit.
:vartype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:ivar effective_date_time: DateTime of the savings plan starts providing benefit from.
:vartype effective_date_time: ~datetime.datetime
:ivar expiry_date_time: Expiry date time.
:vartype expiry_date_time: ~datetime.datetime
:ivar purchase_date_time: Date time when the savings plan was purchased.
:vartype purchase_date_time: ~datetime.datetime
:ivar benefit_start_time: This is the DateTime when the savings plan benefit started.
:vartype benefit_start_time: ~datetime.datetime
:ivar extended_status_info:
:vartype extended_status_info: ~azure.mgmt.billingbenefits.models.ExtendedStatusInfo
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar utilization: Savings plan utilization.
:vartype utilization: ~azure.mgmt.billingbenefits.models.Utilization
:ivar renew_source: SavingsPlan Id of the SavingsPlan from which this SavingsPlan is renewed.
:vartype renew_source: str
:ivar renew_destination: SavingsPlan Id of the SavingsPlan which is purchased because of renew.
:vartype renew_destination: str
:ivar renew_properties:
:vartype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"provisioning_state": {"readonly": True},
"display_provisioning_state": {"readonly": True},
"billing_profile_id": {"readonly": True},
"customer_id": {"readonly": True},
"billing_account_id": {"readonly": True},
"user_friendly_applied_scope_type": {"readonly": True},
"effective_date_time": {"readonly": True},
"expiry_date_time": {"readonly": True},
"purchase_date_time": {"readonly": True},
"extended_status_info": {"readonly": True},
"utilization": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"display_name": {"key": "properties.displayName", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"display_provisioning_state": {"key": "properties.displayProvisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"billing_profile_id": {"key": "properties.billingProfileId", "type": "str"},
"customer_id": {"key": "properties.customerId", "type": "str"},
"billing_account_id": {"key": "properties.billingAccountId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"user_friendly_applied_scope_type": {"key": "properties.userFriendlyAppliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"commitment": {"key": "properties.commitment", "type": "Commitment"},
"effective_date_time": {"key": "properties.effectiveDateTime", "type": "iso-8601"},
"expiry_date_time": {"key": "properties.expiryDateTime", "type": "iso-8601"},
"purchase_date_time": {"key": "properties.purchaseDateTime", "type": "iso-8601"},
"benefit_start_time": {"key": "properties.benefitStartTime", "type": "iso-8601"},
"extended_status_info": {"key": "properties.extendedStatusInfo", "type": "ExtendedStatusInfo"},
"renew": {"key": "properties.renew", "type": "bool"},
"utilization": {"key": "properties.utilization", "type": "Utilization"},
"renew_source": {"key": "properties.renewSource", "type": "str"},
"renew_destination": {"key": "properties.renewDestination", "type": "str"},
"renew_properties": {"key": "properties.renewProperties", "type": "RenewProperties"},
}
def __init__( # pylint: disable=too-many-locals
self,
*,
sku: "_models.Sku",
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
commitment: Optional["_models.Commitment"] = None,
benefit_start_time: Optional[datetime.datetime] = None,
renew: bool = False,
renew_source: Optional[str] = None,
renew_destination: Optional[str] = None,
renew_properties: Optional["_models.RenewProperties"] = None,
**kwargs
):
"""
:keyword sku: Savings plan SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword commitment: Commitment towards the benefit.
:paramtype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:keyword benefit_start_time: This is the DateTime when the savings plan benefit started.
:paramtype benefit_start_time: ~datetime.datetime
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword renew_source: SavingsPlan Id of the SavingsPlan from which this SavingsPlan is
renewed.
:paramtype renew_source: str
:keyword renew_destination: SavingsPlan Id of the SavingsPlan which is purchased because of
renew.
:paramtype renew_destination: str
:keyword renew_properties:
:paramtype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.display_name = display_name
self.provisioning_state = None
self.display_provisioning_state = None
self.billing_scope_id = billing_scope_id
self.billing_profile_id = None
self.customer_id = None
self.billing_account_id = None
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.user_friendly_applied_scope_type = None
self.applied_scope_properties = applied_scope_properties
self.commitment = commitment
self.effective_date_time = None
self.expiry_date_time = None
self.purchase_date_time = None
self.benefit_start_time = benefit_start_time
self.extended_status_info = None
self.renew = renew
self.utilization = None
self.renew_source = renew_source
self.renew_destination = renew_destination
self.renew_properties = renew_properties
class SavingsPlanModelList(_serialization.Model):
"""SavingsPlanModelList.
:ivar value:
:vartype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:ivar next_link: Url to get the next page.
:vartype next_link: str
"""
_attribute_map = {
"value": {"key": "value", "type": "[SavingsPlanModel]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(
self, *, value: Optional[List["_models.SavingsPlanModel"]] = None, next_link: Optional[str] = None, **kwargs
):
"""
:keyword value:
:paramtype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:keyword next_link: Url to get the next page.
:paramtype next_link: str
"""
super().__init__(**kwargs)
self.value = value
self.next_link = next_link
class SavingsPlanModelListResult(_serialization.Model):
"""SavingsPlanModelListResult.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: The list of savings plans.
:vartype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:ivar next_link: Url to get the next page.
:vartype next_link: str
:ivar additional_properties: The roll out count summary of the savings plans.
:vartype additional_properties: list[~azure.mgmt.billingbenefits.models.SavingsPlanSummary]
"""
_validation = {
"value": {"readonly": True},
"next_link": {"readonly": True},
"additional_properties": {"readonly": True},
}
_attribute_map = {
"value": {"key": "value", "type": "[SavingsPlanModel]"},
"next_link": {"key": "nextLink", "type": "str"},
"additional_properties": {"key": "additionalProperties", "type": "[SavingsPlanSummary]"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.value = None
self.next_link = None
self.additional_properties = None
class SavingsPlanOrderAliasModel(Resource): # pylint: disable=too-many-instance-attributes
"""Savings plan order alias.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Savings plan SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar kind: Resource provider kind.
:vartype kind: str
:ivar display_name: Display name.
:vartype display_name: str
:ivar savings_plan_order_id: Identifier of the savings plan created.
:vartype savings_plan_order_id: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar commitment: Commitment towards the benefit.
:vartype commitment: ~azure.mgmt.billingbenefits.models.Commitment
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"savings_plan_order_id": {"readonly": True},
"provisioning_state": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"kind": {"key": "kind", "type": "str"},
"display_name": {"key": "properties.displayName", "type": "str"},
"savings_plan_order_id": {"key": "properties.savingsPlanOrderId", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"commitment": {"key": "properties.commitment", "type": "Commitment"},
}
def __init__(
self,
*,
sku: "_models.Sku",
kind: Optional[str] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
commitment: Optional["_models.Commitment"] = None,
**kwargs
):
"""
:keyword sku: Savings plan SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword kind: Resource provider kind.
:paramtype kind: str
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword commitment: Commitment towards the benefit.
:paramtype commitment: ~azure.mgmt.billingbenefits.models.Commitment
"""
super().__init__(**kwargs)
self.sku = sku
self.kind = kind
self.display_name = display_name
self.savings_plan_order_id = None
self.provisioning_state = None
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.commitment = commitment
class SavingsPlanOrderModel(Resource): # pylint: disable=too-many-instance-attributes
"""Savings plan order.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Savings plan SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar display_name: Display name.
:vartype display_name: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar billing_profile_id: Fully-qualified identifier of the billing profile where the savings
plan is applied. Present only for Field-led or Customer-led customers.
:vartype billing_profile_id: str
:ivar customer_id: Fully-qualified identifier of the customer where the savings plan is
applied. Present only for Partner-led customers.
:vartype customer_id: str
:ivar billing_account_id: Fully-qualified identifier of the billing account where the savings
plan is applied. Present only for Enterprise Agreement customers.
:vartype billing_account_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar expiry_date_time: Expiry date time.
:vartype expiry_date_time: ~datetime.datetime
:ivar benefit_start_time: This is the DateTime when the savings plan benefit started.
:vartype benefit_start_time: ~datetime.datetime
:ivar plan_information: Information describing the type of billing plan for this savings plan.
:vartype plan_information: ~azure.mgmt.billingbenefits.models.BillingPlanInformation
:ivar savings_plans:
:vartype savings_plans: list[str]
:ivar extended_status_info:
:vartype extended_status_info: ~azure.mgmt.billingbenefits.models.ExtendedStatusInfo
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"provisioning_state": {"readonly": True},
"billing_profile_id": {"readonly": True},
"customer_id": {"readonly": True},
"billing_account_id": {"readonly": True},
"expiry_date_time": {"readonly": True},
"extended_status_info": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"display_name": {"key": "properties.displayName", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"billing_profile_id": {"key": "properties.billingProfileId", "type": "str"},
"customer_id": {"key": "properties.customerId", "type": "str"},
"billing_account_id": {"key": "properties.billingAccountId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"expiry_date_time": {"key": "properties.expiryDateTime", "type": "iso-8601"},
"benefit_start_time": {"key": "properties.benefitStartTime", "type": "iso-8601"},
"plan_information": {"key": "properties.planInformation", "type": "BillingPlanInformation"},
"savings_plans": {"key": "properties.savingsPlans", "type": "[str]"},
"extended_status_info": {"key": "properties.extendedStatusInfo", "type": "ExtendedStatusInfo"},
}
def __init__(
self,
*,
sku: "_models.Sku",
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
benefit_start_time: Optional[datetime.datetime] = None,
plan_information: Optional["_models.BillingPlanInformation"] = None,
savings_plans: Optional[List[str]] = None,
**kwargs
):
"""
:keyword sku: Savings plan SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword benefit_start_time: This is the DateTime when the savings plan benefit started.
:paramtype benefit_start_time: ~datetime.datetime
:keyword plan_information: Information describing the type of billing plan for this savings
plan.
:paramtype plan_information: ~azure.mgmt.billingbenefits.models.BillingPlanInformation
:keyword savings_plans:
:paramtype savings_plans: list[str]
"""
super().__init__(**kwargs)
self.sku = sku
self.display_name = display_name
self.provisioning_state = None
self.billing_scope_id = billing_scope_id
self.billing_profile_id = None
self.customer_id = None
self.billing_account_id = None
self.term = term
self.billing_plan = billing_plan
self.expiry_date_time = None
self.benefit_start_time = benefit_start_time
self.plan_information = plan_information
self.savings_plans = savings_plans
self.extended_status_info = None
class SavingsPlanOrderModelList(_serialization.Model):
"""SavingsPlanOrderModelList.
:ivar value:
:vartype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:ivar next_link: Url to get the next page.
:vartype next_link: str
"""
_attribute_map = {
"value": {"key": "value", "type": "[SavingsPlanOrderModel]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(
self,
*,
value: Optional[List["_models.SavingsPlanOrderModel"]] = None,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword value:
:paramtype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:keyword next_link: Url to get the next page.
:paramtype next_link: str
"""
super().__init__(**kwargs)
self.value = value
self.next_link = next_link
class SavingsPlanPurchaseValidateRequest(_serialization.Model):
"""SavingsPlanPurchaseValidateRequest.
:ivar benefits:
:vartype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
"""
_attribute_map = {
"benefits": {"key": "benefits", "type": "[SavingsPlanOrderAliasModel]"},
}
def __init__(self, *, benefits: Optional[List["_models.SavingsPlanOrderAliasModel"]] = None, **kwargs):
"""
:keyword benefits:
:paramtype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
"""
super().__init__(**kwargs)
self.benefits = benefits
class SavingsPlanSummary(_serialization.Model):
"""Savings plans list summary.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: This property has value 'summary'.
:vartype name: str
:ivar value: The roll up count summary of savings plans in each state.
:vartype value: ~azure.mgmt.billingbenefits.models.SavingsPlanSummaryCount
"""
_validation = {
"name": {"readonly": True},
}
_attribute_map = {
"name": {"key": "name", "type": "str"},
"value": {"key": "value", "type": "SavingsPlanSummaryCount"},
}
def __init__(self, *, value: Optional["_models.SavingsPlanSummaryCount"] = None, **kwargs):
"""
:keyword value: The roll up count summary of savings plans in each state.
:paramtype value: ~azure.mgmt.billingbenefits.models.SavingsPlanSummaryCount
"""
super().__init__(**kwargs)
self.name = None
self.value = value
class SavingsPlanSummaryCount(_serialization.Model):
"""The roll up count summary of savings plans in each state.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar succeeded_count: The number of savings plans in Succeeded state.
:vartype succeeded_count: float
:ivar failed_count: The number of savings plans in Failed state.
:vartype failed_count: float
:ivar expiring_count: The number of savings plans in Expiring state.
:vartype expiring_count: float
:ivar expired_count: The number of savings plans in Expired state.
:vartype expired_count: float
:ivar pending_count: The number of savings plans in Pending state.
:vartype pending_count: float
:ivar cancelled_count: The number of savings plans in Cancelled state.
:vartype cancelled_count: float
:ivar processing_count: The number of savings plans in Processing state.
:vartype processing_count: float
:ivar no_benefit_count: The number of savings plans in No Benefit state.
:vartype no_benefit_count: float
:ivar warning_count: The number of savings plans in Warning state.
:vartype warning_count: float
"""
_validation = {
"succeeded_count": {"readonly": True},
"failed_count": {"readonly": True},
"expiring_count": {"readonly": True},
"expired_count": {"readonly": True},
"pending_count": {"readonly": True},
"cancelled_count": {"readonly": True},
"processing_count": {"readonly": True},
"no_benefit_count": {"readonly": True},
"warning_count": {"readonly": True},
}
_attribute_map = {
"succeeded_count": {"key": "succeededCount", "type": "float"},
"failed_count": {"key": "failedCount", "type": "float"},
"expiring_count": {"key": "expiringCount", "type": "float"},
"expired_count": {"key": "expiredCount", "type": "float"},
"pending_count": {"key": "pendingCount", "type": "float"},
"cancelled_count": {"key": "cancelledCount", "type": "float"},
"processing_count": {"key": "processingCount", "type": "float"},
"no_benefit_count": {"key": "noBenefitCount", "type": "float"},
"warning_count": {"key": "warningCount", "type": "float"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.succeeded_count = None
self.failed_count = None
self.expiring_count = None
self.expired_count = None
self.pending_count = None
self.cancelled_count = None
self.processing_count = None
self.no_benefit_count = None
self.warning_count = None
class SavingsPlanUpdateRequest(_serialization.Model):
"""Savings plan patch request.
:ivar properties: Savings plan patch request.
:vartype properties: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties
"""
_attribute_map = {
"properties": {"key": "properties", "type": "SavingsPlanUpdateRequestProperties"},
}
def __init__(self, *, properties: Optional["_models.SavingsPlanUpdateRequestProperties"] = None, **kwargs):
"""
:keyword properties: Savings plan patch request.
:paramtype properties: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties
"""
super().__init__(**kwargs)
self.properties = properties
class SavingsPlanUpdateRequestProperties(_serialization.Model):
"""Savings plan patch request.
:ivar display_name: Display name.
:vartype display_name: str
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar renew_properties:
:vartype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
_attribute_map = {
"display_name": {"key": "displayName", "type": "str"},
"applied_scope_type": {"key": "appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "appliedScopeProperties", "type": "AppliedScopeProperties"},
"renew": {"key": "renew", "type": "bool"},
"renew_properties": {"key": "renewProperties", "type": "RenewProperties"},
}
def __init__(
self,
*,
display_name: Optional[str] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
renew: bool = False,
renew_properties: Optional["_models.RenewProperties"] = None,
**kwargs
):
"""
:keyword display_name: Display name.
:paramtype display_name: str
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword renew_properties:
:paramtype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
super().__init__(**kwargs)
self.display_name = display_name
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.renew = renew
self.renew_properties = renew_properties
class SavingsPlanUpdateValidateRequest(_serialization.Model):
"""SavingsPlanUpdateValidateRequest.
:ivar benefits:
:vartype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties]
"""
_attribute_map = {
"benefits": {"key": "benefits", "type": "[SavingsPlanUpdateRequestProperties]"},
}
def __init__(self, *, benefits: Optional[List["_models.SavingsPlanUpdateRequestProperties"]] = None, **kwargs):
"""
:keyword benefits:
:paramtype benefits:
list[~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties]
"""
super().__init__(**kwargs)
self.benefits = benefits
class SavingsPlanValidateResponse(_serialization.Model):
"""SavingsPlanValidateResponse.
:ivar benefits:
:vartype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanValidResponseProperty]
:ivar next_link: Url to get the next page.
:vartype next_link: str
"""
_attribute_map = {
"benefits": {"key": "benefits", "type": "[SavingsPlanValidResponseProperty]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(
self,
*,
benefits: Optional[List["_models.SavingsPlanValidResponseProperty"]] = None,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword benefits:
:paramtype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanValidResponseProperty]
:keyword next_link: Url to get the next page.
:paramtype next_link: str
"""
super().__init__(**kwargs)
self.benefits = benefits
self.next_link = next_link
class SavingsPlanValidResponseProperty(_serialization.Model):
"""Benefit scope response property.
:ivar valid: Indicates if the provided input was valid.
:vartype valid: bool
:ivar reason_code: Failure reason code if the provided input was invalid.
:vartype reason_code: str
:ivar reason: Failure reason if the provided input was invalid.
:vartype reason: str
"""
_attribute_map = {
"valid": {"key": "valid", "type": "bool"},
"reason_code": {"key": "reasonCode", "type": "str"},
"reason": {"key": "reason", "type": "str"},
}
def __init__(
self, *, valid: Optional[bool] = None, reason_code: Optional[str] = None, reason: Optional[str] = None, **kwargs
):
"""
:keyword valid: Indicates if the provided input was valid.
:paramtype valid: bool
:keyword reason_code: Failure reason code if the provided input was invalid.
:paramtype reason_code: str
:keyword reason: Failure reason if the provided input was invalid.
:paramtype reason: str
"""
super().__init__(**kwargs)
self.valid = valid
self.reason_code = reason_code
self.reason = reason
class Sku(_serialization.Model):
"""The SKU to be applied for this resource.
:ivar name: Name of the SKU to be applied.
:vartype name: str
"""
_attribute_map = {
"name": {"key": "name", "type": "str"},
}
def __init__(self, *, name: Optional[str] = None, **kwargs):
"""
:keyword name: Name of the SKU to be applied.
:paramtype name: str
"""
super().__init__(**kwargs)
self.name = name
class SystemData(_serialization.Model):
"""Metadata pertaining to creation and last modification of the resource.
:ivar created_by: The identity that created the resource.
:vartype created_by: str
:ivar created_by_type: The type of identity that created the resource. Known values are:
"User", "Application", "ManagedIdentity", and "Key".
:vartype created_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:ivar created_at: The timestamp of resource creation (UTC).
:vartype created_at: ~datetime.datetime
:ivar last_modified_by: The identity that last modified the resource.
:vartype last_modified_by: str
:ivar last_modified_by_type: The type of identity that last modified the resource. Known values
are: "User", "Application", "ManagedIdentity", and "Key".
:vartype last_modified_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:ivar last_modified_at: The timestamp of resource last modification (UTC).
:vartype last_modified_at: ~datetime.datetime
"""
_attribute_map = {
"created_by": {"key": "createdBy", "type": "str"},
"created_by_type": {"key": "createdByType", "type": "str"},
"created_at": {"key": "createdAt", "type": "iso-8601"},
"last_modified_by": {"key": "lastModifiedBy", "type": "str"},
"last_modified_by_type": {"key": "lastModifiedByType", "type": "str"},
"last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"},
}
def __init__(
self,
*,
created_by: Optional[str] = None,
created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None,
created_at: Optional[datetime.datetime] = None,
last_modified_by: Optional[str] = None,
last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None,
last_modified_at: Optional[datetime.datetime] = None,
**kwargs
):
"""
:keyword created_by: The identity that created the resource.
:paramtype created_by: str
:keyword created_by_type: The type of identity that created the resource. Known values are:
"User", "Application", "ManagedIdentity", and "Key".
:paramtype created_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:keyword created_at: The timestamp of resource creation (UTC).
:paramtype created_at: ~datetime.datetime
:keyword last_modified_by: The identity that last modified the resource.
:paramtype last_modified_by: str
:keyword last_modified_by_type: The type of identity that last modified the resource. Known
values are: "User", "Application", "ManagedIdentity", and "Key".
:paramtype last_modified_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:keyword last_modified_at: The timestamp of resource last modification (UTC).
:paramtype last_modified_at: ~datetime.datetime
"""
super().__init__(**kwargs)
self.created_by = created_by
self.created_by_type = created_by_type
self.created_at = created_at
self.last_modified_by = last_modified_by
self.last_modified_by_type = last_modified_by_type
self.last_modified_at = last_modified_at
class Utilization(_serialization.Model):
"""Savings plan utilization.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar trend: The number of days trend for a savings plan.
:vartype trend: str
:ivar aggregates: The array of aggregates of a savings plan's utilization.
:vartype aggregates: list[~azure.mgmt.billingbenefits.models.UtilizationAggregates]
"""
_validation = {
"trend": {"readonly": True},
}
_attribute_map = {
"trend": {"key": "trend", "type": "str"},
"aggregates": {"key": "aggregates", "type": "[UtilizationAggregates]"},
}
def __init__(self, *, aggregates: Optional[List["_models.UtilizationAggregates"]] = None, **kwargs):
"""
:keyword aggregates: The array of aggregates of a savings plan's utilization.
:paramtype aggregates: list[~azure.mgmt.billingbenefits.models.UtilizationAggregates]
"""
super().__init__(**kwargs)
self.trend = None
self.aggregates = aggregates
class UtilizationAggregates(_serialization.Model):
"""The aggregate values of savings plan utilization.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar grain: The grain of the aggregate.
:vartype grain: float
:ivar grain_unit: The grain unit of the aggregate.
:vartype grain_unit: str
:ivar value: The aggregate value.
:vartype value: float
:ivar value_unit: The aggregate value unit.
:vartype value_unit: str
"""
_validation = {
"grain": {"readonly": True},
"grain_unit": {"readonly": True},
"value": {"readonly": True},
"value_unit": {"readonly": True},
}
_attribute_map = {
"grain": {"key": "grain", "type": "float"},
"grain_unit": {"key": "grainUnit", "type": "str"},
"value": {"key": "value", "type": "float"},
"value_unit": {"key": "valueUnit", "type": "str"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.grain = None
self.grain_unit = None
self.value = None
self.value_unit = None
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/models/_models_py3.py
|
_models_py3.py
|
import datetime
from typing import List, Optional, TYPE_CHECKING, Union
from .. import _serialization
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from .. import models as _models
class AppliedScopeProperties(_serialization.Model):
"""Properties specific to applied scope type. Not required if not applicable.
:ivar tenant_id: Tenant ID where the benefit is applied.
:vartype tenant_id: str
:ivar management_group_id: Fully-qualified identifier of the management group where the benefit
must be applied.
:vartype management_group_id: str
:ivar subscription_id: Fully-qualified identifier of the subscription.
:vartype subscription_id: str
:ivar resource_group_id: Fully-qualified identifier of the resource group.
:vartype resource_group_id: str
:ivar display_name: Display name.
:vartype display_name: str
"""
_attribute_map = {
"tenant_id": {"key": "tenantId", "type": "str"},
"management_group_id": {"key": "managementGroupId", "type": "str"},
"subscription_id": {"key": "subscriptionId", "type": "str"},
"resource_group_id": {"key": "resourceGroupId", "type": "str"},
"display_name": {"key": "displayName", "type": "str"},
}
def __init__(
self,
*,
tenant_id: Optional[str] = None,
management_group_id: Optional[str] = None,
subscription_id: Optional[str] = None,
resource_group_id: Optional[str] = None,
display_name: Optional[str] = None,
**kwargs
):
"""
:keyword tenant_id: Tenant ID where the benefit is applied.
:paramtype tenant_id: str
:keyword management_group_id: Fully-qualified identifier of the management group where the
benefit must be applied.
:paramtype management_group_id: str
:keyword subscription_id: Fully-qualified identifier of the subscription.
:paramtype subscription_id: str
:keyword resource_group_id: Fully-qualified identifier of the resource group.
:paramtype resource_group_id: str
:keyword display_name: Display name.
:paramtype display_name: str
"""
super().__init__(**kwargs)
self.tenant_id = tenant_id
self.management_group_id = management_group_id
self.subscription_id = subscription_id
self.resource_group_id = resource_group_id
self.display_name = display_name
class BillingInformation(_serialization.Model):
"""billing information.
:ivar billing_currency_total_paid_amount:
:vartype billing_currency_total_paid_amount: ~azure.mgmt.billingbenefits.models.Price
:ivar billing_currency_prorated_amount:
:vartype billing_currency_prorated_amount: ~azure.mgmt.billingbenefits.models.Price
:ivar billing_currency_remaining_commitment_amount:
:vartype billing_currency_remaining_commitment_amount: ~azure.mgmt.billingbenefits.models.Price
"""
_attribute_map = {
"billing_currency_total_paid_amount": {"key": "billingCurrencyTotalPaidAmount", "type": "Price"},
"billing_currency_prorated_amount": {"key": "billingCurrencyProratedAmount", "type": "Price"},
"billing_currency_remaining_commitment_amount": {
"key": "billingCurrencyRemainingCommitmentAmount",
"type": "Price",
},
}
def __init__(
self,
*,
billing_currency_total_paid_amount: Optional["_models.Price"] = None,
billing_currency_prorated_amount: Optional["_models.Price"] = None,
billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None,
**kwargs
):
"""
:keyword billing_currency_total_paid_amount:
:paramtype billing_currency_total_paid_amount: ~azure.mgmt.billingbenefits.models.Price
:keyword billing_currency_prorated_amount:
:paramtype billing_currency_prorated_amount: ~azure.mgmt.billingbenefits.models.Price
:keyword billing_currency_remaining_commitment_amount:
:paramtype billing_currency_remaining_commitment_amount:
~azure.mgmt.billingbenefits.models.Price
"""
super().__init__(**kwargs)
self.billing_currency_total_paid_amount = billing_currency_total_paid_amount
self.billing_currency_prorated_amount = billing_currency_prorated_amount
self.billing_currency_remaining_commitment_amount = billing_currency_remaining_commitment_amount
class BillingPlanInformation(_serialization.Model):
"""Information describing the type of billing plan for this savings plan.
:ivar pricing_currency_total: Amount of money to be paid for the Order. Tax is not included.
:vartype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:ivar start_date: Date when the billing plan has started.
:vartype start_date: ~datetime.date
:ivar next_payment_due_date: For recurring billing plans, indicates the date when next payment
will be processed. Null when total is paid off.
:vartype next_payment_due_date: ~datetime.date
:ivar transactions:
:vartype transactions: list[~azure.mgmt.billingbenefits.models.PaymentDetail]
"""
_attribute_map = {
"pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"},
"start_date": {"key": "startDate", "type": "date"},
"next_payment_due_date": {"key": "nextPaymentDueDate", "type": "date"},
"transactions": {"key": "transactions", "type": "[PaymentDetail]"},
}
def __init__(
self,
*,
pricing_currency_total: Optional["_models.Price"] = None,
start_date: Optional[datetime.date] = None,
next_payment_due_date: Optional[datetime.date] = None,
transactions: Optional[List["_models.PaymentDetail"]] = None,
**kwargs
):
"""
:keyword pricing_currency_total: Amount of money to be paid for the Order. Tax is not included.
:paramtype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:keyword start_date: Date when the billing plan has started.
:paramtype start_date: ~datetime.date
:keyword next_payment_due_date: For recurring billing plans, indicates the date when next
payment will be processed. Null when total is paid off.
:paramtype next_payment_due_date: ~datetime.date
:keyword transactions:
:paramtype transactions: list[~azure.mgmt.billingbenefits.models.PaymentDetail]
"""
super().__init__(**kwargs)
self.pricing_currency_total = pricing_currency_total
self.start_date = start_date
self.next_payment_due_date = next_payment_due_date
self.transactions = transactions
class Price(_serialization.Model):
"""Price.
:ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase
record.
:vartype currency_code: str
:ivar amount:
:vartype amount: float
"""
_attribute_map = {
"currency_code": {"key": "currencyCode", "type": "str"},
"amount": {"key": "amount", "type": "float"},
}
def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs):
"""
:keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this
purchase record.
:paramtype currency_code: str
:keyword amount:
:paramtype amount: float
"""
super().__init__(**kwargs)
self.currency_code = currency_code
self.amount = amount
class Commitment(Price):
"""Commitment towards the benefit.
:ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase
record.
:vartype currency_code: str
:ivar amount:
:vartype amount: float
:ivar grain: Commitment grain. "Hourly"
:vartype grain: str or ~azure.mgmt.billingbenefits.models.CommitmentGrain
"""
_attribute_map = {
"currency_code": {"key": "currencyCode", "type": "str"},
"amount": {"key": "amount", "type": "float"},
"grain": {"key": "grain", "type": "str"},
}
def __init__(
self,
*,
currency_code: Optional[str] = None,
amount: Optional[float] = None,
grain: Optional[Union[str, "_models.CommitmentGrain"]] = None,
**kwargs
):
"""
:keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this
purchase record.
:paramtype currency_code: str
:keyword amount:
:paramtype amount: float
:keyword grain: Commitment grain. "Hourly"
:paramtype grain: str or ~azure.mgmt.billingbenefits.models.CommitmentGrain
"""
super().__init__(currency_code=currency_code, amount=amount, **kwargs)
self.grain = grain
class ErrorAdditionalInfo(_serialization.Model):
"""The resource management error additional info.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar type: The additional info type.
:vartype type: str
:ivar info: The additional info.
:vartype info: JSON
"""
_validation = {
"type": {"readonly": True},
"info": {"readonly": True},
}
_attribute_map = {
"type": {"key": "type", "type": "str"},
"info": {"key": "info", "type": "object"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.type = None
self.info = None
class ErrorDetail(_serialization.Model):
"""The error detail.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: The error code.
:vartype code: str
:ivar message: The error message.
:vartype message: str
:ivar target: The error target.
:vartype target: str
:ivar details: The error details.
:vartype details: list[~azure.mgmt.billingbenefits.models.ErrorDetail]
:ivar additional_info: The error additional info.
:vartype additional_info: list[~azure.mgmt.billingbenefits.models.ErrorAdditionalInfo]
"""
_validation = {
"code": {"readonly": True},
"message": {"readonly": True},
"target": {"readonly": True},
"details": {"readonly": True},
"additional_info": {"readonly": True},
}
_attribute_map = {
"code": {"key": "code", "type": "str"},
"message": {"key": "message", "type": "str"},
"target": {"key": "target", "type": "str"},
"details": {"key": "details", "type": "[ErrorDetail]"},
"additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.code = None
self.message = None
self.target = None
self.details = None
self.additional_info = None
class ErrorResponse(_serialization.Model):
"""Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.).
:ivar error: The error object.
:vartype error: ~azure.mgmt.billingbenefits.models.ErrorDetail
"""
_attribute_map = {
"error": {"key": "error", "type": "ErrorDetail"},
}
def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs):
"""
:keyword error: The error object.
:paramtype error: ~azure.mgmt.billingbenefits.models.ErrorDetail
"""
super().__init__(**kwargs)
self.error = error
class ExtendedStatusInfo(_serialization.Model):
"""ExtendedStatusInfo.
:ivar status_code: Status code providing additional information.
:vartype status_code: str
:ivar message: The message giving detailed information about the status code.
:vartype message: str
"""
_attribute_map = {
"status_code": {"key": "statusCode", "type": "str"},
"message": {"key": "message", "type": "str"},
}
def __init__(self, *, status_code: Optional[str] = None, message: Optional[str] = None, **kwargs):
"""
:keyword status_code: Status code providing additional information.
:paramtype status_code: str
:keyword message: The message giving detailed information about the status code.
:paramtype message: str
"""
super().__init__(**kwargs)
self.status_code = status_code
self.message = message
class Operation(_serialization.Model):
"""Details of a REST API operation, returned from the Resource Provider Operations API.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples:
"Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action".
:vartype name: str
:ivar is_data_action: Whether the operation applies to data-plane. This is "true" for
data-plane operations and "false" for ARM/control-plane operations.
:vartype is_data_action: bool
:ivar display: Localized display information for this particular operation.
:vartype display: ~azure.mgmt.billingbenefits.models.OperationDisplay
:ivar origin: The intended executor of the operation; as in Resource Based Access Control
(RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system",
and "user,system".
:vartype origin: str or ~azure.mgmt.billingbenefits.models.Origin
:ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for
internal only APIs. "Internal"
:vartype action_type: str or ~azure.mgmt.billingbenefits.models.ActionType
"""
_validation = {
"name": {"readonly": True},
"is_data_action": {"readonly": True},
"origin": {"readonly": True},
"action_type": {"readonly": True},
}
_attribute_map = {
"name": {"key": "name", "type": "str"},
"is_data_action": {"key": "isDataAction", "type": "bool"},
"display": {"key": "display", "type": "OperationDisplay"},
"origin": {"key": "origin", "type": "str"},
"action_type": {"key": "actionType", "type": "str"},
}
def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs):
"""
:keyword display: Localized display information for this particular operation.
:paramtype display: ~azure.mgmt.billingbenefits.models.OperationDisplay
"""
super().__init__(**kwargs)
self.name = None
self.is_data_action = None
self.display = display
self.origin = None
self.action_type = None
class OperationDisplay(_serialization.Model):
"""Localized display information for this particular operation.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft
Monitoring Insights" or "Microsoft Compute".
:vartype provider: str
:ivar resource: The localized friendly name of the resource type related to this operation.
E.g. "Virtual Machines" or "Job Schedule Collections".
:vartype resource: str
:ivar operation: The concise, localized friendly name for the operation; suitable for
dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine".
:vartype operation: str
:ivar description: The short, localized friendly description of the operation; suitable for
tool tips and detailed views.
:vartype description: str
"""
_validation = {
"provider": {"readonly": True},
"resource": {"readonly": True},
"operation": {"readonly": True},
"description": {"readonly": True},
}
_attribute_map = {
"provider": {"key": "provider", "type": "str"},
"resource": {"key": "resource", "type": "str"},
"operation": {"key": "operation", "type": "str"},
"description": {"key": "description", "type": "str"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.provider = None
self.resource = None
self.operation = None
self.description = None
class OperationListResult(_serialization.Model):
"""A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: List of operations supported by the resource provider.
:vartype value: list[~azure.mgmt.billingbenefits.models.Operation]
:ivar next_link: URL to get the next set of operation list results (if there are any).
:vartype next_link: str
"""
_validation = {
"value": {"readonly": True},
"next_link": {"readonly": True},
}
_attribute_map = {
"value": {"key": "value", "type": "[Operation]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.value = None
self.next_link = None
class OperationResultError(_serialization.Model):
"""Required if status == failed or status == canceled.
:ivar code: Required if status == failed or status == cancelled. If status == failed, provide
an invariant error code used for error troubleshooting, aggregation, and analysis.
:vartype code: str
:ivar message: Required if status == failed. Localized. If status == failed, provide an
actionable error message indicating what error occurred, and what the user can do to address
the issue.
:vartype message: str
"""
_attribute_map = {
"code": {"key": "code", "type": "str"},
"message": {"key": "message", "type": "str"},
}
def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs):
"""
:keyword code: Required if status == failed or status == cancelled. If status == failed,
provide an invariant error code used for error troubleshooting, aggregation, and analysis.
:paramtype code: str
:keyword message: Required if status == failed. Localized. If status == failed, provide an
actionable error message indicating what error occurred, and what the user can do to address
the issue.
:paramtype message: str
"""
super().__init__(**kwargs)
self.code = code
self.message = message
class PaymentDetail(_serialization.Model):
"""Information about payment related to a savings plan order.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar due_date: Date when the payment needs to be done.
:vartype due_date: ~datetime.date
:ivar payment_date: Date when the transaction is completed. Is null when it is scheduled.
:vartype payment_date: ~datetime.date
:ivar pricing_currency_total: Amount in pricing currency. Tax not included.
:vartype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:ivar billing_currency_total: Amount charged in Billing currency. Tax not included. Is null for
future payments.
:vartype billing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:ivar status: Describes whether the payment is completed, failed, cancelled or scheduled in the
future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled".
:vartype status: str or ~azure.mgmt.billingbenefits.models.PaymentStatus
:ivar extended_status_info:
:vartype extended_status_info: ~azure.mgmt.billingbenefits.models.ExtendedStatusInfo
:ivar billing_account: Billing account.
:vartype billing_account: str
"""
_validation = {
"extended_status_info": {"readonly": True},
}
_attribute_map = {
"due_date": {"key": "dueDate", "type": "date"},
"payment_date": {"key": "paymentDate", "type": "date"},
"pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"},
"billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"},
"status": {"key": "status", "type": "str"},
"extended_status_info": {"key": "extendedStatusInfo", "type": "ExtendedStatusInfo"},
"billing_account": {"key": "billingAccount", "type": "str"},
}
def __init__(
self,
*,
due_date: Optional[datetime.date] = None,
payment_date: Optional[datetime.date] = None,
pricing_currency_total: Optional["_models.Price"] = None,
billing_currency_total: Optional["_models.Price"] = None,
status: Optional[Union[str, "_models.PaymentStatus"]] = None,
billing_account: Optional[str] = None,
**kwargs
):
"""
:keyword due_date: Date when the payment needs to be done.
:paramtype due_date: ~datetime.date
:keyword payment_date: Date when the transaction is completed. Is null when it is scheduled.
:paramtype payment_date: ~datetime.date
:keyword pricing_currency_total: Amount in pricing currency. Tax not included.
:paramtype pricing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:keyword billing_currency_total: Amount charged in Billing currency. Tax not included. Is null
for future payments.
:paramtype billing_currency_total: ~azure.mgmt.billingbenefits.models.Price
:keyword status: Describes whether the payment is completed, failed, cancelled or scheduled in
the future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled".
:paramtype status: str or ~azure.mgmt.billingbenefits.models.PaymentStatus
:keyword billing_account: Billing account.
:paramtype billing_account: str
"""
super().__init__(**kwargs)
self.due_date = due_date
self.payment_date = payment_date
self.pricing_currency_total = pricing_currency_total
self.billing_currency_total = billing_currency_total
self.status = status
self.extended_status_info = None
self.billing_account = billing_account
class PricingCurrencyTotal(Price):
"""PricingCurrencyTotal.
:ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase
record.
:vartype currency_code: str
:ivar amount:
:vartype amount: float
:ivar duration: Represents either billing plan or savings plan term in ISO 8601 format. Known
values are: "P1M", "P1Y", and "P3Y".
:vartype duration: str or ~azure.mgmt.billingbenefits.models.PricingCurrencyDuration
"""
_attribute_map = {
"currency_code": {"key": "currencyCode", "type": "str"},
"amount": {"key": "amount", "type": "float"},
"duration": {"key": "duration", "type": "str"},
}
def __init__(
self,
*,
currency_code: Optional[str] = None,
amount: Optional[float] = None,
duration: Optional[Union[str, "_models.PricingCurrencyDuration"]] = None,
**kwargs
):
"""
:keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this
purchase record.
:paramtype currency_code: str
:keyword amount:
:paramtype amount: float
:keyword duration: Represents either billing plan or savings plan term in ISO 8601 format.
Known values are: "P1M", "P1Y", and "P3Y".
:paramtype duration: str or ~azure.mgmt.billingbenefits.models.PricingCurrencyDuration
"""
super().__init__(currency_code=currency_code, amount=amount, **kwargs)
self.duration = duration
class PurchaseRequest(_serialization.Model):
"""PurchaseRequest.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar sku: The SKU to be applied for this resource.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar display_name: Friendly name of the savings plan.
:vartype display_name: str
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar commitment: Commitment towards the benefit.
:vartype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:ivar effective_date_time: DateTime of the savings plan starts providing benefit from.
:vartype effective_date_time: ~datetime.datetime
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
"""
_validation = {
"effective_date_time": {"readonly": True},
}
_attribute_map = {
"sku": {"key": "sku", "type": "Sku"},
"display_name": {"key": "properties.displayName", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"commitment": {"key": "properties.commitment", "type": "Commitment"},
"effective_date_time": {"key": "properties.effectiveDateTime", "type": "iso-8601"},
"renew": {"key": "properties.renew", "type": "bool"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
}
def __init__(
self,
*,
sku: Optional["_models.Sku"] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
commitment: Optional["_models.Commitment"] = None,
renew: bool = False,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
**kwargs
):
"""
:keyword sku: The SKU to be applied for this resource.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword display_name: Friendly name of the savings plan.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword commitment: Commitment towards the benefit.
:paramtype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.display_name = display_name
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.commitment = commitment
self.effective_date_time = None
self.renew = renew
self.applied_scope_properties = applied_scope_properties
class RenewProperties(_serialization.Model):
"""RenewProperties.
:ivar purchase_properties:
:vartype purchase_properties: ~azure.mgmt.billingbenefits.models.PurchaseRequest
"""
_attribute_map = {
"purchase_properties": {"key": "purchaseProperties", "type": "PurchaseRequest"},
}
def __init__(self, *, purchase_properties: Optional["_models.PurchaseRequest"] = None, **kwargs):
"""
:keyword purchase_properties:
:paramtype purchase_properties: ~azure.mgmt.billingbenefits.models.PurchaseRequest
"""
super().__init__(**kwargs)
self.purchase_properties = purchase_properties
class Resource(_serialization.Model):
"""Common fields that are returned in the response for all Azure Resource Manager resources.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.id = None
self.name = None
self.type = None
self.system_data = None
class ReservationOrderAliasRequest(Resource): # pylint: disable=too-many-instance-attributes
"""Reservation order alias.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Reservation order SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar location: The Azure Region where the reservation benefits are applied to.
:vartype location: str
:ivar display_name: Display name.
:vartype display_name: str
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar quantity: Total Quantity of the SKUs purchased in the Reservation.
:vartype quantity: int
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:vartype reserved_resource_type: str or ~azure.mgmt.billingbenefits.models.ReservedResourceType
:ivar review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be
reviewed.
:vartype review_date_time: ~datetime.datetime
:ivar reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:vartype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequestPropertiesReservedResourceProperties
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"quantity": {"minimum": 1},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"location": {"key": "location", "type": "str"},
"display_name": {"key": "properties.displayName", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"quantity": {"key": "properties.quantity", "type": "int"},
"renew": {"key": "properties.renew", "type": "bool"},
"reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"},
"review_date_time": {"key": "properties.reviewDateTime", "type": "iso-8601"},
"reserved_resource_properties": {
"key": "properties.reservedResourceProperties",
"type": "ReservationOrderAliasRequestPropertiesReservedResourceProperties",
},
}
def __init__(
self,
*,
sku: "_models.Sku",
location: Optional[str] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
quantity: Optional[int] = None,
renew: bool = False,
reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None,
review_date_time: Optional[datetime.datetime] = None,
reserved_resource_properties: Optional[
"_models.ReservationOrderAliasRequestPropertiesReservedResourceProperties"
] = None,
**kwargs
):
"""
:keyword sku: Reservation order SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword location: The Azure Region where the reservation benefits are applied to.
:paramtype location: str
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword quantity: Total Quantity of the SKUs purchased in the Reservation.
:paramtype quantity: int
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:paramtype reserved_resource_type: str or
~azure.mgmt.billingbenefits.models.ReservedResourceType
:keyword review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be
reviewed.
:paramtype review_date_time: ~datetime.datetime
:keyword reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:paramtype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasRequestPropertiesReservedResourceProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.location = location
self.display_name = display_name
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.quantity = quantity
self.renew = renew
self.reserved_resource_type = reserved_resource_type
self.review_date_time = review_date_time
self.reserved_resource_properties = reserved_resource_properties
class ReservationOrderAliasRequestPropertiesReservedResourceProperties(_serialization.Model):
"""Properties specific to each reserved resource type. Not required if not applicable.
:ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in
the same VM size group. Known values are: "On" and "Off".
:vartype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
_attribute_map = {
"instance_flexibility": {"key": "instanceFlexibility", "type": "str"},
}
def __init__(self, *, instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, **kwargs):
"""
:keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs
in the same VM size group. Known values are: "On" and "Off".
:paramtype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
super().__init__(**kwargs)
self.instance_flexibility = instance_flexibility
class ReservationOrderAliasResponse(Resource): # pylint: disable=too-many-instance-attributes
"""Reservation order alias.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Reservation order SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar location: The Azure Region where the reserved resource lives.
:vartype location: str
:ivar display_name: Display name.
:vartype display_name: str
:ivar reservation_order_id: Identifier of the reservation order created.
:vartype reservation_order_id: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar quantity: Total Quantity of the SKUs purchased in the Reservation.
:vartype quantity: int
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:vartype reserved_resource_type: str or ~azure.mgmt.billingbenefits.models.ReservedResourceType
:ivar review_date_time: This is the date-time when the Reservation needs to be reviewed.
:vartype review_date_time: ~datetime.datetime
:ivar reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:vartype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponsePropertiesReservedResourceProperties
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"reservation_order_id": {"readonly": True},
"provisioning_state": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"location": {"key": "location", "type": "str"},
"display_name": {"key": "properties.displayName", "type": "str"},
"reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"quantity": {"key": "properties.quantity", "type": "int"},
"renew": {"key": "properties.renew", "type": "bool"},
"reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"},
"review_date_time": {"key": "properties.reviewDateTime", "type": "iso-8601"},
"reserved_resource_properties": {
"key": "properties.reservedResourceProperties",
"type": "ReservationOrderAliasResponsePropertiesReservedResourceProperties",
},
}
def __init__(
self,
*,
sku: "_models.Sku",
location: Optional[str] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
quantity: Optional[int] = None,
renew: bool = False,
reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None,
review_date_time: Optional[datetime.datetime] = None,
reserved_resource_properties: Optional[
"_models.ReservationOrderAliasResponsePropertiesReservedResourceProperties"
] = None,
**kwargs
):
"""
:keyword sku: Reservation order SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword location: The Azure Region where the reserved resource lives.
:paramtype location: str
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword quantity: Total Quantity of the SKUs purchased in the Reservation.
:paramtype quantity: int
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword reserved_resource_type: The type of the resource that is being reserved. Known values
are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse",
"VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob",
"RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost",
"SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles",
"SqlEdge", and "VirtualMachineSoftware".
:paramtype reserved_resource_type: str or
~azure.mgmt.billingbenefits.models.ReservedResourceType
:keyword review_date_time: This is the date-time when the Reservation needs to be reviewed.
:paramtype review_date_time: ~datetime.datetime
:keyword reserved_resource_properties: Properties specific to each reserved resource type. Not
required if not applicable.
:paramtype reserved_resource_properties:
~azure.mgmt.billingbenefits.models.ReservationOrderAliasResponsePropertiesReservedResourceProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.location = location
self.display_name = display_name
self.reservation_order_id = None
self.provisioning_state = None
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.quantity = quantity
self.renew = renew
self.reserved_resource_type = reserved_resource_type
self.review_date_time = review_date_time
self.reserved_resource_properties = reserved_resource_properties
class ReservationOrderAliasResponsePropertiesReservedResourceProperties(_serialization.Model):
"""Properties specific to each reserved resource type. Not required if not applicable.
:ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in
the same VM size group. Known values are: "On" and "Off".
:vartype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
_attribute_map = {
"instance_flexibility": {"key": "instanceFlexibility", "type": "str"},
}
def __init__(self, *, instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, **kwargs):
"""
:keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs
in the same VM size group. Known values are: "On" and "Off".
:paramtype instance_flexibility: str or ~azure.mgmt.billingbenefits.models.InstanceFlexibility
"""
super().__init__(**kwargs)
self.instance_flexibility = instance_flexibility
class RoleAssignmentEntity(_serialization.Model):
"""Role assignment entity.
:ivar id: Role assignment entity id.
:vartype id: str
:ivar name: Role assignment entity name.
:vartype name: str
:ivar principal_id: Principal Id.
:vartype principal_id: str
:ivar role_definition_id: Role definition id.
:vartype role_definition_id: str
:ivar scope: Scope of the role assignment entity.
:vartype scope: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"principal_id": {"key": "properties.principalId", "type": "str"},
"role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"},
"scope": {"key": "properties.scope", "type": "str"},
}
def __init__(
self,
*,
id: Optional[str] = None, # pylint: disable=redefined-builtin
name: Optional[str] = None,
principal_id: Optional[str] = None,
role_definition_id: Optional[str] = None,
scope: Optional[str] = None,
**kwargs
):
"""
:keyword id: Role assignment entity id.
:paramtype id: str
:keyword name: Role assignment entity name.
:paramtype name: str
:keyword principal_id: Principal Id.
:paramtype principal_id: str
:keyword role_definition_id: Role definition id.
:paramtype role_definition_id: str
:keyword scope: Scope of the role assignment entity.
:paramtype scope: str
"""
super().__init__(**kwargs)
self.id = id
self.name = name
self.principal_id = principal_id
self.role_definition_id = role_definition_id
self.scope = scope
class SavingsPlanModel(Resource): # pylint: disable=too-many-instance-attributes
"""Savings plan.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Savings plan SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar display_name: Display name.
:vartype display_name: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar display_provisioning_state: The provisioning state of the savings plan for display, e.g.
Succeeded.
:vartype display_provisioning_state: str
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar billing_profile_id: Fully-qualified identifier of the billing profile where the savings
plan is applied. Present only for Field-led or Customer-led customers.
:vartype billing_profile_id: str
:ivar customer_id: Fully-qualified identifier of the customer where the savings plan is
applied. Present only for Partner-led customers.
:vartype customer_id: str
:ivar billing_account_id: Fully-qualified identifier of the billing account where the savings
plan is applied. Present only for Enterprise Agreement customers.
:vartype billing_account_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar user_friendly_applied_scope_type: The applied scope type of the savings plan for display,
e.g. Shared.
:vartype user_friendly_applied_scope_type: str
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar commitment: Commitment towards the benefit.
:vartype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:ivar effective_date_time: DateTime of the savings plan starts providing benefit from.
:vartype effective_date_time: ~datetime.datetime
:ivar expiry_date_time: Expiry date time.
:vartype expiry_date_time: ~datetime.datetime
:ivar purchase_date_time: Date time when the savings plan was purchased.
:vartype purchase_date_time: ~datetime.datetime
:ivar benefit_start_time: This is the DateTime when the savings plan benefit started.
:vartype benefit_start_time: ~datetime.datetime
:ivar extended_status_info:
:vartype extended_status_info: ~azure.mgmt.billingbenefits.models.ExtendedStatusInfo
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar utilization: Savings plan utilization.
:vartype utilization: ~azure.mgmt.billingbenefits.models.Utilization
:ivar renew_source: SavingsPlan Id of the SavingsPlan from which this SavingsPlan is renewed.
:vartype renew_source: str
:ivar renew_destination: SavingsPlan Id of the SavingsPlan which is purchased because of renew.
:vartype renew_destination: str
:ivar renew_properties:
:vartype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"provisioning_state": {"readonly": True},
"display_provisioning_state": {"readonly": True},
"billing_profile_id": {"readonly": True},
"customer_id": {"readonly": True},
"billing_account_id": {"readonly": True},
"user_friendly_applied_scope_type": {"readonly": True},
"effective_date_time": {"readonly": True},
"expiry_date_time": {"readonly": True},
"purchase_date_time": {"readonly": True},
"extended_status_info": {"readonly": True},
"utilization": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"display_name": {"key": "properties.displayName", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"display_provisioning_state": {"key": "properties.displayProvisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"billing_profile_id": {"key": "properties.billingProfileId", "type": "str"},
"customer_id": {"key": "properties.customerId", "type": "str"},
"billing_account_id": {"key": "properties.billingAccountId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"user_friendly_applied_scope_type": {"key": "properties.userFriendlyAppliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"commitment": {"key": "properties.commitment", "type": "Commitment"},
"effective_date_time": {"key": "properties.effectiveDateTime", "type": "iso-8601"},
"expiry_date_time": {"key": "properties.expiryDateTime", "type": "iso-8601"},
"purchase_date_time": {"key": "properties.purchaseDateTime", "type": "iso-8601"},
"benefit_start_time": {"key": "properties.benefitStartTime", "type": "iso-8601"},
"extended_status_info": {"key": "properties.extendedStatusInfo", "type": "ExtendedStatusInfo"},
"renew": {"key": "properties.renew", "type": "bool"},
"utilization": {"key": "properties.utilization", "type": "Utilization"},
"renew_source": {"key": "properties.renewSource", "type": "str"},
"renew_destination": {"key": "properties.renewDestination", "type": "str"},
"renew_properties": {"key": "properties.renewProperties", "type": "RenewProperties"},
}
def __init__( # pylint: disable=too-many-locals
self,
*,
sku: "_models.Sku",
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
commitment: Optional["_models.Commitment"] = None,
benefit_start_time: Optional[datetime.datetime] = None,
renew: bool = False,
renew_source: Optional[str] = None,
renew_destination: Optional[str] = None,
renew_properties: Optional["_models.RenewProperties"] = None,
**kwargs
):
"""
:keyword sku: Savings plan SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword commitment: Commitment towards the benefit.
:paramtype commitment: ~azure.mgmt.billingbenefits.models.Commitment
:keyword benefit_start_time: This is the DateTime when the savings plan benefit started.
:paramtype benefit_start_time: ~datetime.datetime
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword renew_source: SavingsPlan Id of the SavingsPlan from which this SavingsPlan is
renewed.
:paramtype renew_source: str
:keyword renew_destination: SavingsPlan Id of the SavingsPlan which is purchased because of
renew.
:paramtype renew_destination: str
:keyword renew_properties:
:paramtype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
super().__init__(**kwargs)
self.sku = sku
self.display_name = display_name
self.provisioning_state = None
self.display_provisioning_state = None
self.billing_scope_id = billing_scope_id
self.billing_profile_id = None
self.customer_id = None
self.billing_account_id = None
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.user_friendly_applied_scope_type = None
self.applied_scope_properties = applied_scope_properties
self.commitment = commitment
self.effective_date_time = None
self.expiry_date_time = None
self.purchase_date_time = None
self.benefit_start_time = benefit_start_time
self.extended_status_info = None
self.renew = renew
self.utilization = None
self.renew_source = renew_source
self.renew_destination = renew_destination
self.renew_properties = renew_properties
class SavingsPlanModelList(_serialization.Model):
"""SavingsPlanModelList.
:ivar value:
:vartype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:ivar next_link: Url to get the next page.
:vartype next_link: str
"""
_attribute_map = {
"value": {"key": "value", "type": "[SavingsPlanModel]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(
self, *, value: Optional[List["_models.SavingsPlanModel"]] = None, next_link: Optional[str] = None, **kwargs
):
"""
:keyword value:
:paramtype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:keyword next_link: Url to get the next page.
:paramtype next_link: str
"""
super().__init__(**kwargs)
self.value = value
self.next_link = next_link
class SavingsPlanModelListResult(_serialization.Model):
"""SavingsPlanModelListResult.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: The list of savings plans.
:vartype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanModel]
:ivar next_link: Url to get the next page.
:vartype next_link: str
:ivar additional_properties: The roll out count summary of the savings plans.
:vartype additional_properties: list[~azure.mgmt.billingbenefits.models.SavingsPlanSummary]
"""
_validation = {
"value": {"readonly": True},
"next_link": {"readonly": True},
"additional_properties": {"readonly": True},
}
_attribute_map = {
"value": {"key": "value", "type": "[SavingsPlanModel]"},
"next_link": {"key": "nextLink", "type": "str"},
"additional_properties": {"key": "additionalProperties", "type": "[SavingsPlanSummary]"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.value = None
self.next_link = None
self.additional_properties = None
class SavingsPlanOrderAliasModel(Resource): # pylint: disable=too-many-instance-attributes
"""Savings plan order alias.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Savings plan SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar kind: Resource provider kind.
:vartype kind: str
:ivar display_name: Display name.
:vartype display_name: str
:ivar savings_plan_order_id: Identifier of the savings plan created.
:vartype savings_plan_order_id: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar commitment: Commitment towards the benefit.
:vartype commitment: ~azure.mgmt.billingbenefits.models.Commitment
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"savings_plan_order_id": {"readonly": True},
"provisioning_state": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"kind": {"key": "kind", "type": "str"},
"display_name": {"key": "properties.displayName", "type": "str"},
"savings_plan_order_id": {"key": "properties.savingsPlanOrderId", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"},
"commitment": {"key": "properties.commitment", "type": "Commitment"},
}
def __init__(
self,
*,
sku: "_models.Sku",
kind: Optional[str] = None,
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
commitment: Optional["_models.Commitment"] = None,
**kwargs
):
"""
:keyword sku: Savings plan SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword kind: Resource provider kind.
:paramtype kind: str
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword commitment: Commitment towards the benefit.
:paramtype commitment: ~azure.mgmt.billingbenefits.models.Commitment
"""
super().__init__(**kwargs)
self.sku = sku
self.kind = kind
self.display_name = display_name
self.savings_plan_order_id = None
self.provisioning_state = None
self.billing_scope_id = billing_scope_id
self.term = term
self.billing_plan = billing_plan
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.commitment = commitment
class SavingsPlanOrderModel(Resource): # pylint: disable=too-many-instance-attributes
"""Savings plan order.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy
information.
:vartype system_data: ~azure.mgmt.billingbenefits.models.SystemData
:ivar sku: Savings plan SKU. Required.
:vartype sku: ~azure.mgmt.billingbenefits.models.Sku
:ivar display_name: Display name.
:vartype display_name: str
:ivar provisioning_state: Provisioning state. Known values are: "Creating", "PendingBilling",
"ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", and "Failed".
:vartype provisioning_state: str or ~azure.mgmt.billingbenefits.models.ProvisioningState
:ivar billing_scope_id: Subscription that will be charged for purchasing the benefit.
:vartype billing_scope_id: str
:ivar billing_profile_id: Fully-qualified identifier of the billing profile where the savings
plan is applied. Present only for Field-led or Customer-led customers.
:vartype billing_profile_id: str
:ivar customer_id: Fully-qualified identifier of the customer where the savings plan is
applied. Present only for Partner-led customers.
:vartype customer_id: str
:ivar billing_account_id: Fully-qualified identifier of the billing account where the savings
plan is applied. Present only for Enterprise Agreement customers.
:vartype billing_account_id: str
:ivar term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:vartype term: str or ~azure.mgmt.billingbenefits.models.Term
:ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly
billing plans. "P1M"
:vartype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:ivar expiry_date_time: Expiry date time.
:vartype expiry_date_time: ~datetime.datetime
:ivar benefit_start_time: This is the DateTime when the savings plan benefit started.
:vartype benefit_start_time: ~datetime.datetime
:ivar plan_information: Information describing the type of billing plan for this savings plan.
:vartype plan_information: ~azure.mgmt.billingbenefits.models.BillingPlanInformation
:ivar savings_plans:
:vartype savings_plans: list[str]
:ivar extended_status_info:
:vartype extended_status_info: ~azure.mgmt.billingbenefits.models.ExtendedStatusInfo
"""
_validation = {
"id": {"readonly": True},
"name": {"readonly": True},
"type": {"readonly": True},
"system_data": {"readonly": True},
"sku": {"required": True},
"provisioning_state": {"readonly": True},
"billing_profile_id": {"readonly": True},
"customer_id": {"readonly": True},
"billing_account_id": {"readonly": True},
"expiry_date_time": {"readonly": True},
"extended_status_info": {"readonly": True},
}
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"type": {"key": "type", "type": "str"},
"system_data": {"key": "systemData", "type": "SystemData"},
"sku": {"key": "sku", "type": "Sku"},
"display_name": {"key": "properties.displayName", "type": "str"},
"provisioning_state": {"key": "properties.provisioningState", "type": "str"},
"billing_scope_id": {"key": "properties.billingScopeId", "type": "str"},
"billing_profile_id": {"key": "properties.billingProfileId", "type": "str"},
"customer_id": {"key": "properties.customerId", "type": "str"},
"billing_account_id": {"key": "properties.billingAccountId", "type": "str"},
"term": {"key": "properties.term", "type": "str"},
"billing_plan": {"key": "properties.billingPlan", "type": "str"},
"expiry_date_time": {"key": "properties.expiryDateTime", "type": "iso-8601"},
"benefit_start_time": {"key": "properties.benefitStartTime", "type": "iso-8601"},
"plan_information": {"key": "properties.planInformation", "type": "BillingPlanInformation"},
"savings_plans": {"key": "properties.savingsPlans", "type": "[str]"},
"extended_status_info": {"key": "properties.extendedStatusInfo", "type": "ExtendedStatusInfo"},
}
def __init__(
self,
*,
sku: "_models.Sku",
display_name: Optional[str] = None,
billing_scope_id: Optional[str] = None,
term: Optional[Union[str, "_models.Term"]] = None,
billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None,
benefit_start_time: Optional[datetime.datetime] = None,
plan_information: Optional["_models.BillingPlanInformation"] = None,
savings_plans: Optional[List[str]] = None,
**kwargs
):
"""
:keyword sku: Savings plan SKU. Required.
:paramtype sku: ~azure.mgmt.billingbenefits.models.Sku
:keyword display_name: Display name.
:paramtype display_name: str
:keyword billing_scope_id: Subscription that will be charged for purchasing the benefit.
:paramtype billing_scope_id: str
:keyword term: Represent benefit term in ISO 8601 format. Known values are: "P1Y", "P3Y", and
"P5Y".
:paramtype term: str or ~azure.mgmt.billingbenefits.models.Term
:keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for
monthly billing plans. "P1M"
:paramtype billing_plan: str or ~azure.mgmt.billingbenefits.models.BillingPlan
:keyword benefit_start_time: This is the DateTime when the savings plan benefit started.
:paramtype benefit_start_time: ~datetime.datetime
:keyword plan_information: Information describing the type of billing plan for this savings
plan.
:paramtype plan_information: ~azure.mgmt.billingbenefits.models.BillingPlanInformation
:keyword savings_plans:
:paramtype savings_plans: list[str]
"""
super().__init__(**kwargs)
self.sku = sku
self.display_name = display_name
self.provisioning_state = None
self.billing_scope_id = billing_scope_id
self.billing_profile_id = None
self.customer_id = None
self.billing_account_id = None
self.term = term
self.billing_plan = billing_plan
self.expiry_date_time = None
self.benefit_start_time = benefit_start_time
self.plan_information = plan_information
self.savings_plans = savings_plans
self.extended_status_info = None
class SavingsPlanOrderModelList(_serialization.Model):
"""SavingsPlanOrderModelList.
:ivar value:
:vartype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:ivar next_link: Url to get the next page.
:vartype next_link: str
"""
_attribute_map = {
"value": {"key": "value", "type": "[SavingsPlanOrderModel]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(
self,
*,
value: Optional[List["_models.SavingsPlanOrderModel"]] = None,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword value:
:paramtype value: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderModel]
:keyword next_link: Url to get the next page.
:paramtype next_link: str
"""
super().__init__(**kwargs)
self.value = value
self.next_link = next_link
class SavingsPlanPurchaseValidateRequest(_serialization.Model):
"""SavingsPlanPurchaseValidateRequest.
:ivar benefits:
:vartype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
"""
_attribute_map = {
"benefits": {"key": "benefits", "type": "[SavingsPlanOrderAliasModel]"},
}
def __init__(self, *, benefits: Optional[List["_models.SavingsPlanOrderAliasModel"]] = None, **kwargs):
"""
:keyword benefits:
:paramtype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanOrderAliasModel]
"""
super().__init__(**kwargs)
self.benefits = benefits
class SavingsPlanSummary(_serialization.Model):
"""Savings plans list summary.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: This property has value 'summary'.
:vartype name: str
:ivar value: The roll up count summary of savings plans in each state.
:vartype value: ~azure.mgmt.billingbenefits.models.SavingsPlanSummaryCount
"""
_validation = {
"name": {"readonly": True},
}
_attribute_map = {
"name": {"key": "name", "type": "str"},
"value": {"key": "value", "type": "SavingsPlanSummaryCount"},
}
def __init__(self, *, value: Optional["_models.SavingsPlanSummaryCount"] = None, **kwargs):
"""
:keyword value: The roll up count summary of savings plans in each state.
:paramtype value: ~azure.mgmt.billingbenefits.models.SavingsPlanSummaryCount
"""
super().__init__(**kwargs)
self.name = None
self.value = value
class SavingsPlanSummaryCount(_serialization.Model):
"""The roll up count summary of savings plans in each state.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar succeeded_count: The number of savings plans in Succeeded state.
:vartype succeeded_count: float
:ivar failed_count: The number of savings plans in Failed state.
:vartype failed_count: float
:ivar expiring_count: The number of savings plans in Expiring state.
:vartype expiring_count: float
:ivar expired_count: The number of savings plans in Expired state.
:vartype expired_count: float
:ivar pending_count: The number of savings plans in Pending state.
:vartype pending_count: float
:ivar cancelled_count: The number of savings plans in Cancelled state.
:vartype cancelled_count: float
:ivar processing_count: The number of savings plans in Processing state.
:vartype processing_count: float
:ivar no_benefit_count: The number of savings plans in No Benefit state.
:vartype no_benefit_count: float
:ivar warning_count: The number of savings plans in Warning state.
:vartype warning_count: float
"""
_validation = {
"succeeded_count": {"readonly": True},
"failed_count": {"readonly": True},
"expiring_count": {"readonly": True},
"expired_count": {"readonly": True},
"pending_count": {"readonly": True},
"cancelled_count": {"readonly": True},
"processing_count": {"readonly": True},
"no_benefit_count": {"readonly": True},
"warning_count": {"readonly": True},
}
_attribute_map = {
"succeeded_count": {"key": "succeededCount", "type": "float"},
"failed_count": {"key": "failedCount", "type": "float"},
"expiring_count": {"key": "expiringCount", "type": "float"},
"expired_count": {"key": "expiredCount", "type": "float"},
"pending_count": {"key": "pendingCount", "type": "float"},
"cancelled_count": {"key": "cancelledCount", "type": "float"},
"processing_count": {"key": "processingCount", "type": "float"},
"no_benefit_count": {"key": "noBenefitCount", "type": "float"},
"warning_count": {"key": "warningCount", "type": "float"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.succeeded_count = None
self.failed_count = None
self.expiring_count = None
self.expired_count = None
self.pending_count = None
self.cancelled_count = None
self.processing_count = None
self.no_benefit_count = None
self.warning_count = None
class SavingsPlanUpdateRequest(_serialization.Model):
"""Savings plan patch request.
:ivar properties: Savings plan patch request.
:vartype properties: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties
"""
_attribute_map = {
"properties": {"key": "properties", "type": "SavingsPlanUpdateRequestProperties"},
}
def __init__(self, *, properties: Optional["_models.SavingsPlanUpdateRequestProperties"] = None, **kwargs):
"""
:keyword properties: Savings plan patch request.
:paramtype properties: ~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties
"""
super().__init__(**kwargs)
self.properties = properties
class SavingsPlanUpdateRequestProperties(_serialization.Model):
"""Savings plan patch request.
:ivar display_name: Display name.
:vartype display_name: str
:ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and
"ManagementGroup".
:vartype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:ivar applied_scope_properties: Properties specific to applied scope type. Not required if not
applicable.
:vartype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:ivar renew: Setting this to true will automatically purchase a new benefit on the expiration
date time.
:vartype renew: bool
:ivar renew_properties:
:vartype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
_attribute_map = {
"display_name": {"key": "displayName", "type": "str"},
"applied_scope_type": {"key": "appliedScopeType", "type": "str"},
"applied_scope_properties": {"key": "appliedScopeProperties", "type": "AppliedScopeProperties"},
"renew": {"key": "renew", "type": "bool"},
"renew_properties": {"key": "renewProperties", "type": "RenewProperties"},
}
def __init__(
self,
*,
display_name: Optional[str] = None,
applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None,
applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None,
renew: bool = False,
renew_properties: Optional["_models.RenewProperties"] = None,
**kwargs
):
"""
:keyword display_name: Display name.
:paramtype display_name: str
:keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared",
and "ManagementGroup".
:paramtype applied_scope_type: str or ~azure.mgmt.billingbenefits.models.AppliedScopeType
:keyword applied_scope_properties: Properties specific to applied scope type. Not required if
not applicable.
:paramtype applied_scope_properties: ~azure.mgmt.billingbenefits.models.AppliedScopeProperties
:keyword renew: Setting this to true will automatically purchase a new benefit on the
expiration date time.
:paramtype renew: bool
:keyword renew_properties:
:paramtype renew_properties: ~azure.mgmt.billingbenefits.models.RenewProperties
"""
super().__init__(**kwargs)
self.display_name = display_name
self.applied_scope_type = applied_scope_type
self.applied_scope_properties = applied_scope_properties
self.renew = renew
self.renew_properties = renew_properties
class SavingsPlanUpdateValidateRequest(_serialization.Model):
"""SavingsPlanUpdateValidateRequest.
:ivar benefits:
:vartype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties]
"""
_attribute_map = {
"benefits": {"key": "benefits", "type": "[SavingsPlanUpdateRequestProperties]"},
}
def __init__(self, *, benefits: Optional[List["_models.SavingsPlanUpdateRequestProperties"]] = None, **kwargs):
"""
:keyword benefits:
:paramtype benefits:
list[~azure.mgmt.billingbenefits.models.SavingsPlanUpdateRequestProperties]
"""
super().__init__(**kwargs)
self.benefits = benefits
class SavingsPlanValidateResponse(_serialization.Model):
"""SavingsPlanValidateResponse.
:ivar benefits:
:vartype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanValidResponseProperty]
:ivar next_link: Url to get the next page.
:vartype next_link: str
"""
_attribute_map = {
"benefits": {"key": "benefits", "type": "[SavingsPlanValidResponseProperty]"},
"next_link": {"key": "nextLink", "type": "str"},
}
def __init__(
self,
*,
benefits: Optional[List["_models.SavingsPlanValidResponseProperty"]] = None,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword benefits:
:paramtype benefits: list[~azure.mgmt.billingbenefits.models.SavingsPlanValidResponseProperty]
:keyword next_link: Url to get the next page.
:paramtype next_link: str
"""
super().__init__(**kwargs)
self.benefits = benefits
self.next_link = next_link
class SavingsPlanValidResponseProperty(_serialization.Model):
"""Benefit scope response property.
:ivar valid: Indicates if the provided input was valid.
:vartype valid: bool
:ivar reason_code: Failure reason code if the provided input was invalid.
:vartype reason_code: str
:ivar reason: Failure reason if the provided input was invalid.
:vartype reason: str
"""
_attribute_map = {
"valid": {"key": "valid", "type": "bool"},
"reason_code": {"key": "reasonCode", "type": "str"},
"reason": {"key": "reason", "type": "str"},
}
def __init__(
self, *, valid: Optional[bool] = None, reason_code: Optional[str] = None, reason: Optional[str] = None, **kwargs
):
"""
:keyword valid: Indicates if the provided input was valid.
:paramtype valid: bool
:keyword reason_code: Failure reason code if the provided input was invalid.
:paramtype reason_code: str
:keyword reason: Failure reason if the provided input was invalid.
:paramtype reason: str
"""
super().__init__(**kwargs)
self.valid = valid
self.reason_code = reason_code
self.reason = reason
class Sku(_serialization.Model):
"""The SKU to be applied for this resource.
:ivar name: Name of the SKU to be applied.
:vartype name: str
"""
_attribute_map = {
"name": {"key": "name", "type": "str"},
}
def __init__(self, *, name: Optional[str] = None, **kwargs):
"""
:keyword name: Name of the SKU to be applied.
:paramtype name: str
"""
super().__init__(**kwargs)
self.name = name
class SystemData(_serialization.Model):
"""Metadata pertaining to creation and last modification of the resource.
:ivar created_by: The identity that created the resource.
:vartype created_by: str
:ivar created_by_type: The type of identity that created the resource. Known values are:
"User", "Application", "ManagedIdentity", and "Key".
:vartype created_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:ivar created_at: The timestamp of resource creation (UTC).
:vartype created_at: ~datetime.datetime
:ivar last_modified_by: The identity that last modified the resource.
:vartype last_modified_by: str
:ivar last_modified_by_type: The type of identity that last modified the resource. Known values
are: "User", "Application", "ManagedIdentity", and "Key".
:vartype last_modified_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:ivar last_modified_at: The timestamp of resource last modification (UTC).
:vartype last_modified_at: ~datetime.datetime
"""
_attribute_map = {
"created_by": {"key": "createdBy", "type": "str"},
"created_by_type": {"key": "createdByType", "type": "str"},
"created_at": {"key": "createdAt", "type": "iso-8601"},
"last_modified_by": {"key": "lastModifiedBy", "type": "str"},
"last_modified_by_type": {"key": "lastModifiedByType", "type": "str"},
"last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"},
}
def __init__(
self,
*,
created_by: Optional[str] = None,
created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None,
created_at: Optional[datetime.datetime] = None,
last_modified_by: Optional[str] = None,
last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None,
last_modified_at: Optional[datetime.datetime] = None,
**kwargs
):
"""
:keyword created_by: The identity that created the resource.
:paramtype created_by: str
:keyword created_by_type: The type of identity that created the resource. Known values are:
"User", "Application", "ManagedIdentity", and "Key".
:paramtype created_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:keyword created_at: The timestamp of resource creation (UTC).
:paramtype created_at: ~datetime.datetime
:keyword last_modified_by: The identity that last modified the resource.
:paramtype last_modified_by: str
:keyword last_modified_by_type: The type of identity that last modified the resource. Known
values are: "User", "Application", "ManagedIdentity", and "Key".
:paramtype last_modified_by_type: str or ~azure.mgmt.billingbenefits.models.CreatedByType
:keyword last_modified_at: The timestamp of resource last modification (UTC).
:paramtype last_modified_at: ~datetime.datetime
"""
super().__init__(**kwargs)
self.created_by = created_by
self.created_by_type = created_by_type
self.created_at = created_at
self.last_modified_by = last_modified_by
self.last_modified_by_type = last_modified_by_type
self.last_modified_at = last_modified_at
class Utilization(_serialization.Model):
"""Savings plan utilization.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar trend: The number of days trend for a savings plan.
:vartype trend: str
:ivar aggregates: The array of aggregates of a savings plan's utilization.
:vartype aggregates: list[~azure.mgmt.billingbenefits.models.UtilizationAggregates]
"""
_validation = {
"trend": {"readonly": True},
}
_attribute_map = {
"trend": {"key": "trend", "type": "str"},
"aggregates": {"key": "aggregates", "type": "[UtilizationAggregates]"},
}
def __init__(self, *, aggregates: Optional[List["_models.UtilizationAggregates"]] = None, **kwargs):
"""
:keyword aggregates: The array of aggregates of a savings plan's utilization.
:paramtype aggregates: list[~azure.mgmt.billingbenefits.models.UtilizationAggregates]
"""
super().__init__(**kwargs)
self.trend = None
self.aggregates = aggregates
class UtilizationAggregates(_serialization.Model):
"""The aggregate values of savings plan utilization.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar grain: The grain of the aggregate.
:vartype grain: float
:ivar grain_unit: The grain unit of the aggregate.
:vartype grain_unit: str
:ivar value: The aggregate value.
:vartype value: float
:ivar value_unit: The aggregate value unit.
:vartype value_unit: str
"""
_validation = {
"grain": {"readonly": True},
"grain_unit": {"readonly": True},
"value": {"readonly": True},
"value_unit": {"readonly": True},
}
_attribute_map = {
"grain": {"key": "grain", "type": "float"},
"grain_unit": {"key": "grainUnit", "type": "str"},
"value": {"key": "value", "type": "float"},
"value_unit": {"key": "valueUnit", "type": "str"},
}
def __init__(self, **kwargs):
""" """
super().__init__(**kwargs)
self.grain = None
self.grain_unit = None
self.value = None
self.value_unit = None
| 0.886966 | 0.187096 |
from enum import Enum
from azure.core import CaseInsensitiveEnumMeta
class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs."""
INTERNAL = "Internal"
class AppliedScopeType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Type of the Applied Scope."""
SINGLE = "Single"
SHARED = "Shared"
MANAGEMENT_GROUP = "ManagementGroup"
class BillingPlan(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Represents the billing plan in ISO 8601 format. Required only for monthly billing plans."""
P1_M = "P1M"
class CommitmentGrain(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Commitment grain."""
HOURLY = "Hourly"
class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of identity that created the resource."""
USER = "User"
APPLICATION = "Application"
MANAGED_IDENTITY = "ManagedIdentity"
KEY = "Key"
class InstanceFlexibility(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Turning this on will apply the reservation discount to other VMs in the same VM size group."""
ON = "On"
OFF = "Off"
class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit
logs UX. Default value is "user,system".
"""
USER = "user"
SYSTEM = "system"
USER_SYSTEM = "user,system"
class PaymentStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Describes whether the payment is completed, failed, cancelled or scheduled in the future."""
SUCCEEDED = "Succeeded"
FAILED = "Failed"
SCHEDULED = "Scheduled"
CANCELLED = "Cancelled"
class PricingCurrencyDuration(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Represents either billing plan or savings plan term in ISO 8601 format."""
P1_M = "P1M"
P1_Y = "P1Y"
P3_Y = "P3Y"
class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Provisioning state."""
CREATING = "Creating"
PENDING_BILLING = "PendingBilling"
CONFIRMED_BILLING = "ConfirmedBilling"
CREATED = "Created"
SUCCEEDED = "Succeeded"
CANCELLED = "Cancelled"
EXPIRED = "Expired"
FAILED = "Failed"
class ReservedResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of the resource that is being reserved."""
VIRTUAL_MACHINES = "VirtualMachines"
SQL_DATABASES = "SqlDatabases"
SUSE_LINUX = "SuseLinux"
COSMOS_DB = "CosmosDb"
RED_HAT = "RedHat"
SQL_DATA_WAREHOUSE = "SqlDataWarehouse"
V_MWARE_CLOUD_SIMPLE = "VMwareCloudSimple"
RED_HAT_OSA = "RedHatOsa"
DATABRICKS = "Databricks"
APP_SERVICE = "AppService"
MANAGED_DISK = "ManagedDisk"
BLOCK_BLOB = "BlockBlob"
REDIS_CACHE = "RedisCache"
AZURE_DATA_EXPLORER = "AzureDataExplorer"
MY_SQL = "MySql"
MARIA_DB = "MariaDb"
POSTGRE_SQL = "PostgreSql"
DEDICATED_HOST = "DedicatedHost"
SAP_HANA = "SapHana"
SQL_AZURE_HYBRID_BENEFIT = "SqlAzureHybridBenefit"
AVS = "AVS"
DATA_FACTORY = "DataFactory"
NET_APP_STORAGE = "NetAppStorage"
AZURE_FILES = "AzureFiles"
SQL_EDGE = "SqlEdge"
VIRTUAL_MACHINE_SOFTWARE = "VirtualMachineSoftware"
class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Represent benefit term in ISO 8601 format."""
P1_Y = "P1Y"
P3_Y = "P3Y"
P5_Y = "P5Y"
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/models/_billing_benefits_rp_enums.py
|
_billing_benefits_rp_enums.py
|
from enum import Enum
from azure.core import CaseInsensitiveEnumMeta
class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs."""
INTERNAL = "Internal"
class AppliedScopeType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Type of the Applied Scope."""
SINGLE = "Single"
SHARED = "Shared"
MANAGEMENT_GROUP = "ManagementGroup"
class BillingPlan(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Represents the billing plan in ISO 8601 format. Required only for monthly billing plans."""
P1_M = "P1M"
class CommitmentGrain(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Commitment grain."""
HOURLY = "Hourly"
class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of identity that created the resource."""
USER = "User"
APPLICATION = "Application"
MANAGED_IDENTITY = "ManagedIdentity"
KEY = "Key"
class InstanceFlexibility(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Turning this on will apply the reservation discount to other VMs in the same VM size group."""
ON = "On"
OFF = "Off"
class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit
logs UX. Default value is "user,system".
"""
USER = "user"
SYSTEM = "system"
USER_SYSTEM = "user,system"
class PaymentStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Describes whether the payment is completed, failed, cancelled or scheduled in the future."""
SUCCEEDED = "Succeeded"
FAILED = "Failed"
SCHEDULED = "Scheduled"
CANCELLED = "Cancelled"
class PricingCurrencyDuration(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Represents either billing plan or savings plan term in ISO 8601 format."""
P1_M = "P1M"
P1_Y = "P1Y"
P3_Y = "P3Y"
class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Provisioning state."""
CREATING = "Creating"
PENDING_BILLING = "PendingBilling"
CONFIRMED_BILLING = "ConfirmedBilling"
CREATED = "Created"
SUCCEEDED = "Succeeded"
CANCELLED = "Cancelled"
EXPIRED = "Expired"
FAILED = "Failed"
class ReservedResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""The type of the resource that is being reserved."""
VIRTUAL_MACHINES = "VirtualMachines"
SQL_DATABASES = "SqlDatabases"
SUSE_LINUX = "SuseLinux"
COSMOS_DB = "CosmosDb"
RED_HAT = "RedHat"
SQL_DATA_WAREHOUSE = "SqlDataWarehouse"
V_MWARE_CLOUD_SIMPLE = "VMwareCloudSimple"
RED_HAT_OSA = "RedHatOsa"
DATABRICKS = "Databricks"
APP_SERVICE = "AppService"
MANAGED_DISK = "ManagedDisk"
BLOCK_BLOB = "BlockBlob"
REDIS_CACHE = "RedisCache"
AZURE_DATA_EXPLORER = "AzureDataExplorer"
MY_SQL = "MySql"
MARIA_DB = "MariaDb"
POSTGRE_SQL = "PostgreSql"
DEDICATED_HOST = "DedicatedHost"
SAP_HANA = "SapHana"
SQL_AZURE_HYBRID_BENEFIT = "SqlAzureHybridBenefit"
AVS = "AVS"
DATA_FACTORY = "DataFactory"
NET_APP_STORAGE = "NetAppStorage"
AZURE_FILES = "AzureFiles"
SQL_EDGE = "SqlEdge"
VIRTUAL_MACHINE_SOFTWARE = "VirtualMachineSoftware"
class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta):
"""Represent benefit term in ISO 8601 format."""
P1_Y = "P1Y"
P3_Y = "P3Y"
P5_Y = "P5Y"
| 0.835013 | 0.145753 |
from ._models_py3 import AppliedScopeProperties
from ._models_py3 import BillingInformation
from ._models_py3 import BillingPlanInformation
from ._models_py3 import Commitment
from ._models_py3 import ErrorAdditionalInfo
from ._models_py3 import ErrorDetail
from ._models_py3 import ErrorResponse
from ._models_py3 import ExtendedStatusInfo
from ._models_py3 import Operation
from ._models_py3 import OperationDisplay
from ._models_py3 import OperationListResult
from ._models_py3 import OperationResultError
from ._models_py3 import PaymentDetail
from ._models_py3 import Price
from ._models_py3 import PricingCurrencyTotal
from ._models_py3 import PurchaseRequest
from ._models_py3 import RenewProperties
from ._models_py3 import ReservationOrderAliasRequest
from ._models_py3 import ReservationOrderAliasRequestPropertiesReservedResourceProperties
from ._models_py3 import ReservationOrderAliasResponse
from ._models_py3 import ReservationOrderAliasResponsePropertiesReservedResourceProperties
from ._models_py3 import Resource
from ._models_py3 import RoleAssignmentEntity
from ._models_py3 import SavingsPlanModel
from ._models_py3 import SavingsPlanModelList
from ._models_py3 import SavingsPlanModelListResult
from ._models_py3 import SavingsPlanOrderAliasModel
from ._models_py3 import SavingsPlanOrderModel
from ._models_py3 import SavingsPlanOrderModelList
from ._models_py3 import SavingsPlanPurchaseValidateRequest
from ._models_py3 import SavingsPlanSummary
from ._models_py3 import SavingsPlanSummaryCount
from ._models_py3 import SavingsPlanUpdateRequest
from ._models_py3 import SavingsPlanUpdateRequestProperties
from ._models_py3 import SavingsPlanUpdateValidateRequest
from ._models_py3 import SavingsPlanValidResponseProperty
from ._models_py3 import SavingsPlanValidateResponse
from ._models_py3 import Sku
from ._models_py3 import SystemData
from ._models_py3 import Utilization
from ._models_py3 import UtilizationAggregates
from ._billing_benefits_rp_enums import ActionType
from ._billing_benefits_rp_enums import AppliedScopeType
from ._billing_benefits_rp_enums import BillingPlan
from ._billing_benefits_rp_enums import CommitmentGrain
from ._billing_benefits_rp_enums import CreatedByType
from ._billing_benefits_rp_enums import InstanceFlexibility
from ._billing_benefits_rp_enums import Origin
from ._billing_benefits_rp_enums import PaymentStatus
from ._billing_benefits_rp_enums import PricingCurrencyDuration
from ._billing_benefits_rp_enums import ProvisioningState
from ._billing_benefits_rp_enums import ReservedResourceType
from ._billing_benefits_rp_enums import Term
from ._patch import __all__ as _patch_all
from ._patch import * # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"AppliedScopeProperties",
"BillingInformation",
"BillingPlanInformation",
"Commitment",
"ErrorAdditionalInfo",
"ErrorDetail",
"ErrorResponse",
"ExtendedStatusInfo",
"Operation",
"OperationDisplay",
"OperationListResult",
"OperationResultError",
"PaymentDetail",
"Price",
"PricingCurrencyTotal",
"PurchaseRequest",
"RenewProperties",
"ReservationOrderAliasRequest",
"ReservationOrderAliasRequestPropertiesReservedResourceProperties",
"ReservationOrderAliasResponse",
"ReservationOrderAliasResponsePropertiesReservedResourceProperties",
"Resource",
"RoleAssignmentEntity",
"SavingsPlanModel",
"SavingsPlanModelList",
"SavingsPlanModelListResult",
"SavingsPlanOrderAliasModel",
"SavingsPlanOrderModel",
"SavingsPlanOrderModelList",
"SavingsPlanPurchaseValidateRequest",
"SavingsPlanSummary",
"SavingsPlanSummaryCount",
"SavingsPlanUpdateRequest",
"SavingsPlanUpdateRequestProperties",
"SavingsPlanUpdateValidateRequest",
"SavingsPlanValidResponseProperty",
"SavingsPlanValidateResponse",
"Sku",
"SystemData",
"Utilization",
"UtilizationAggregates",
"ActionType",
"AppliedScopeType",
"BillingPlan",
"CommitmentGrain",
"CreatedByType",
"InstanceFlexibility",
"Origin",
"PaymentStatus",
"PricingCurrencyDuration",
"ProvisioningState",
"ReservedResourceType",
"Term",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
|
azure-mgmt-billingbenefits
|
/azure-mgmt-billingbenefits-1.0.0b1.zip/azure-mgmt-billingbenefits-1.0.0b1/azure/mgmt/billingbenefits/models/__init__.py
|
__init__.py
|
from ._models_py3 import AppliedScopeProperties
from ._models_py3 import BillingInformation
from ._models_py3 import BillingPlanInformation
from ._models_py3 import Commitment
from ._models_py3 import ErrorAdditionalInfo
from ._models_py3 import ErrorDetail
from ._models_py3 import ErrorResponse
from ._models_py3 import ExtendedStatusInfo
from ._models_py3 import Operation
from ._models_py3 import OperationDisplay
from ._models_py3 import OperationListResult
from ._models_py3 import OperationResultError
from ._models_py3 import PaymentDetail
from ._models_py3 import Price
from ._models_py3 import PricingCurrencyTotal
from ._models_py3 import PurchaseRequest
from ._models_py3 import RenewProperties
from ._models_py3 import ReservationOrderAliasRequest
from ._models_py3 import ReservationOrderAliasRequestPropertiesReservedResourceProperties
from ._models_py3 import ReservationOrderAliasResponse
from ._models_py3 import ReservationOrderAliasResponsePropertiesReservedResourceProperties
from ._models_py3 import Resource
from ._models_py3 import RoleAssignmentEntity
from ._models_py3 import SavingsPlanModel
from ._models_py3 import SavingsPlanModelList
from ._models_py3 import SavingsPlanModelListResult
from ._models_py3 import SavingsPlanOrderAliasModel
from ._models_py3 import SavingsPlanOrderModel
from ._models_py3 import SavingsPlanOrderModelList
from ._models_py3 import SavingsPlanPurchaseValidateRequest
from ._models_py3 import SavingsPlanSummary
from ._models_py3 import SavingsPlanSummaryCount
from ._models_py3 import SavingsPlanUpdateRequest
from ._models_py3 import SavingsPlanUpdateRequestProperties
from ._models_py3 import SavingsPlanUpdateValidateRequest
from ._models_py3 import SavingsPlanValidResponseProperty
from ._models_py3 import SavingsPlanValidateResponse
from ._models_py3 import Sku
from ._models_py3 import SystemData
from ._models_py3 import Utilization
from ._models_py3 import UtilizationAggregates
from ._billing_benefits_rp_enums import ActionType
from ._billing_benefits_rp_enums import AppliedScopeType
from ._billing_benefits_rp_enums import BillingPlan
from ._billing_benefits_rp_enums import CommitmentGrain
from ._billing_benefits_rp_enums import CreatedByType
from ._billing_benefits_rp_enums import InstanceFlexibility
from ._billing_benefits_rp_enums import Origin
from ._billing_benefits_rp_enums import PaymentStatus
from ._billing_benefits_rp_enums import PricingCurrencyDuration
from ._billing_benefits_rp_enums import ProvisioningState
from ._billing_benefits_rp_enums import ReservedResourceType
from ._billing_benefits_rp_enums import Term
from ._patch import __all__ as _patch_all
from ._patch import * # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"AppliedScopeProperties",
"BillingInformation",
"BillingPlanInformation",
"Commitment",
"ErrorAdditionalInfo",
"ErrorDetail",
"ErrorResponse",
"ExtendedStatusInfo",
"Operation",
"OperationDisplay",
"OperationListResult",
"OperationResultError",
"PaymentDetail",
"Price",
"PricingCurrencyTotal",
"PurchaseRequest",
"RenewProperties",
"ReservationOrderAliasRequest",
"ReservationOrderAliasRequestPropertiesReservedResourceProperties",
"ReservationOrderAliasResponse",
"ReservationOrderAliasResponsePropertiesReservedResourceProperties",
"Resource",
"RoleAssignmentEntity",
"SavingsPlanModel",
"SavingsPlanModelList",
"SavingsPlanModelListResult",
"SavingsPlanOrderAliasModel",
"SavingsPlanOrderModel",
"SavingsPlanOrderModelList",
"SavingsPlanPurchaseValidateRequest",
"SavingsPlanSummary",
"SavingsPlanSummaryCount",
"SavingsPlanUpdateRequest",
"SavingsPlanUpdateRequestProperties",
"SavingsPlanUpdateValidateRequest",
"SavingsPlanValidResponseProperty",
"SavingsPlanValidateResponse",
"Sku",
"SystemData",
"Utilization",
"UtilizationAggregates",
"ActionType",
"AppliedScopeType",
"BillingPlan",
"CommitmentGrain",
"CreatedByType",
"InstanceFlexibility",
"Origin",
"PaymentStatus",
"PricingCurrencyDuration",
"ProvisioningState",
"ReservedResourceType",
"Term",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
| 0.518302 | 0.07088 |
from copy import deepcopy
from typing import Any, Optional, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from msrest import Deserializer, Serializer
from . import models
from ._configuration import AzureBotServiceConfiguration
from .operations import BotConnectionOperations, BotsOperations, ChannelsOperations, DirectLineOperations, HostSettingsOperations, OperationResultsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class AzureBotService:
"""Azure Bot Service is a platform for creating smart conversational agents.
:ivar bots: BotsOperations operations
:vartype bots: azure.mgmt.botservice.operations.BotsOperations
:ivar channels: ChannelsOperations operations
:vartype channels: azure.mgmt.botservice.operations.ChannelsOperations
:ivar direct_line: DirectLineOperations operations
:vartype direct_line: azure.mgmt.botservice.operations.DirectLineOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.botservice.operations.Operations
:ivar bot_connection: BotConnectionOperations operations
:vartype bot_connection: azure.mgmt.botservice.operations.BotConnectionOperations
:ivar host_settings: HostSettingsOperations operations
:vartype host_settings: azure.mgmt.botservice.operations.HostSettingsOperations
:ivar operation_results: OperationResultsOperations operations
:vartype operation_results: azure.mgmt.botservice.operations.OperationResultsOperations
:ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
:vartype private_endpoint_connections:
azure.mgmt.botservice.operations.PrivateEndpointConnectionsOperations
:ivar private_link_resources: PrivateLinkResourcesOperations operations
:vartype private_link_resources:
azure.mgmt.botservice.operations.PrivateLinkResourcesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = AzureBotServiceConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.bots = BotsOperations(self._client, self._config, self._serialize, self._deserialize)
self.channels = ChannelsOperations(self._client, self._config, self._serialize, self._deserialize)
self.direct_line = DirectLineOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.bot_connection = BotConnectionOperations(self._client, self._config, self._serialize, self._deserialize)
self.host_settings = HostSettingsOperations(self._client, self._config, self._serialize, self._deserialize)
self.operation_results = OperationResultsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request, # type: HttpRequest
**kwargs: Any
) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self):
# type: () -> None
self._client.close()
def __enter__(self):
# type: () -> AzureBotService
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/_azure_bot_service.py
|
_azure_bot_service.py
|
from copy import deepcopy
from typing import Any, Optional, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from msrest import Deserializer, Serializer
from . import models
from ._configuration import AzureBotServiceConfiguration
from .operations import BotConnectionOperations, BotsOperations, ChannelsOperations, DirectLineOperations, HostSettingsOperations, OperationResultsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class AzureBotService:
"""Azure Bot Service is a platform for creating smart conversational agents.
:ivar bots: BotsOperations operations
:vartype bots: azure.mgmt.botservice.operations.BotsOperations
:ivar channels: ChannelsOperations operations
:vartype channels: azure.mgmt.botservice.operations.ChannelsOperations
:ivar direct_line: DirectLineOperations operations
:vartype direct_line: azure.mgmt.botservice.operations.DirectLineOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.botservice.operations.Operations
:ivar bot_connection: BotConnectionOperations operations
:vartype bot_connection: azure.mgmt.botservice.operations.BotConnectionOperations
:ivar host_settings: HostSettingsOperations operations
:vartype host_settings: azure.mgmt.botservice.operations.HostSettingsOperations
:ivar operation_results: OperationResultsOperations operations
:vartype operation_results: azure.mgmt.botservice.operations.OperationResultsOperations
:ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
:vartype private_endpoint_connections:
azure.mgmt.botservice.operations.PrivateEndpointConnectionsOperations
:ivar private_link_resources: PrivateLinkResourcesOperations operations
:vartype private_link_resources:
azure.mgmt.botservice.operations.PrivateLinkResourcesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = AzureBotServiceConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.bots = BotsOperations(self._client, self._config, self._serialize, self._deserialize)
self.channels = ChannelsOperations(self._client, self._config, self._serialize, self._deserialize)
self.direct_line = DirectLineOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.bot_connection = BotConnectionOperations(self._client, self._config, self._serialize, self._deserialize)
self.host_settings = HostSettingsOperations(self._client, self._config, self._serialize, self._deserialize)
self.operation_results = OperationResultsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request, # type: HttpRequest
**kwargs: Any
) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self):
# type: () -> None
self._client.close()
def __enter__(self):
# type: () -> AzureBotService
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
| 0.82734 | 0.091261 |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
from ._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class AzureBotServiceConfiguration(Configuration):
"""Configuration for AzureBotService.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
super(AzureBotServiceConfiguration, self).__init__(**kwargs)
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = "2021-05-01-preview"
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'mgmt-botservice/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/_configuration.py
|
_configuration.py
|
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
from ._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class AzureBotServiceConfiguration(Configuration):
"""Configuration for AzureBotService.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
super(AzureBotServiceConfiguration, self).__init__(**kwargs)
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = "2021-05-01-preview"
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'mgmt-botservice/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
| 0.8067 | 0.074164 |
from typing import Optional, List
import importlib
import msrest
class WebChatSite(msrest.serialization.Model):
"""A site for the Webchat channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
"""
super(WebChatSite, self).__init__(
site_name=site_name,
is_enabled=is_enabled,
is_webchat_preview_enabled=is_webchat_preview_enabled,
**kwargs
)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
class DirectLineSite(msrest.serialization.Model):
"""A site for the Direct Line channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_v1_enabled: bool,
is_v3_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
"""
super(DirectLineSite, self).__init__(
site_name=site_name,
is_enabled=is_enabled,
is_v1_enabled=is_v1_enabled,
is_v3_enabled=is_v3_enabled,
is_secure_site_enabled=is_secure_site_enabled,
is_block_user_upload_enabled=is_block_user_upload_enabled,
**kwargs
)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
class Site(WebChatSite, DirectLineSite):
"""A site for the channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
:ivar is_token_enabled: Whether this site is token enabled for channel.
:vartype is_token_enabled: bool
:ivar e_tag: Entity Tag.
:vartype e_tag: str
"""
_validation = {
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
'is_token_enabled': {'key': 'isTokenEnabled', 'type': 'bool'},
'e_tag': {'key': 'eTag', 'type': 'str'},
}
def __init__(
self,
*,
is_v1_enabled: bool,
is_v3_enabled: bool,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
is_token_enabled: Optional[bool] = None,
e_tag: Optional[str] = None,
**kwargs
):
"""
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
:keyword is_token_enabled: Whether this site is token enabled for channel.
:paramtype is_token_enabled: bool
:keyword e_tag: Entity Tag.
:paramtype e_tag: str
"""
super(Site, self).__init__(site_name=site_name, is_enabled=is_enabled,
is_webchat_preview_enabled=is_webchat_preview_enabled, is_v1_enabled=is_v1_enabled,
is_v3_enabled=is_v3_enabled, is_secure_site_enabled=is_secure_site_enabled,
is_block_user_upload_enabled=is_block_user_upload_enabled,
trusted_origins=trusted_origins, **kwargs)
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
# This file is used for handwritten extensions to the generated code. Example:
# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md
def patch_sdk():
curr_package = importlib.import_module("azure.mgmt.botservice")
curr_package.models.WebChatSite = WebChatSite
curr_package.models.DirectLineSite = DirectLineSite
curr_package.models.Site = Site
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/_patch.py
|
_patch.py
|
from typing import Optional, List
import importlib
import msrest
class WebChatSite(msrest.serialization.Model):
"""A site for the Webchat channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
"""
super(WebChatSite, self).__init__(
site_name=site_name,
is_enabled=is_enabled,
is_webchat_preview_enabled=is_webchat_preview_enabled,
**kwargs
)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
class DirectLineSite(msrest.serialization.Model):
"""A site for the Direct Line channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_v1_enabled: bool,
is_v3_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
"""
super(DirectLineSite, self).__init__(
site_name=site_name,
is_enabled=is_enabled,
is_v1_enabled=is_v1_enabled,
is_v3_enabled=is_v3_enabled,
is_secure_site_enabled=is_secure_site_enabled,
is_block_user_upload_enabled=is_block_user_upload_enabled,
**kwargs
)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
class Site(WebChatSite, DirectLineSite):
"""A site for the channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
:ivar is_token_enabled: Whether this site is token enabled for channel.
:vartype is_token_enabled: bool
:ivar e_tag: Entity Tag.
:vartype e_tag: str
"""
_validation = {
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
'is_token_enabled': {'key': 'isTokenEnabled', 'type': 'bool'},
'e_tag': {'key': 'eTag', 'type': 'str'},
}
def __init__(
self,
*,
is_v1_enabled: bool,
is_v3_enabled: bool,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
is_token_enabled: Optional[bool] = None,
e_tag: Optional[str] = None,
**kwargs
):
"""
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
:keyword is_token_enabled: Whether this site is token enabled for channel.
:paramtype is_token_enabled: bool
:keyword e_tag: Entity Tag.
:paramtype e_tag: str
"""
super(Site, self).__init__(site_name=site_name, is_enabled=is_enabled,
is_webchat_preview_enabled=is_webchat_preview_enabled, is_v1_enabled=is_v1_enabled,
is_v3_enabled=is_v3_enabled, is_secure_site_enabled=is_secure_site_enabled,
is_block_user_upload_enabled=is_block_user_upload_enabled,
trusted_origins=trusted_origins, **kwargs)
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
# This file is used for handwritten extensions to the generated code. Example:
# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md
def patch_sdk():
curr_package = importlib.import_module("azure.mgmt.botservice")
curr_package.models.WebChatSite = WebChatSite
curr_package.models.DirectLineSite = DirectLineSite
curr_package.models.Site = Site
| 0.909847 | 0.211946 |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_update_request(
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PATCH",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
channel_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
channel_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_with_keys_request(
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/listChannelWithKeys')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_resource_group_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class ChannelsOperations(object):
"""ChannelsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
parameters: "_models.BotChannel",
**kwargs: Any
) -> "_models.BotChannel":
"""Creates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.BotChannel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'BotChannel')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def update(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.Channel"] = None,
**kwargs: Any
) -> "_models.BotChannel":
"""Updates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot channel resource.
:type properties: ~azure.mgmt.botservice.models.Channel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.BotChannel(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'BotChannel')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> None:
"""Deletes a Channel registration from a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> "_models.BotChannel":
"""Returns a BotService Channel registration specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def list_with_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
**kwargs: Any
) -> "_models.ListChannelWithKeysResponse":
"""Lists a Channel registration for a Bot Service including secrets.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ListChannelWithKeysResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ListChannelWithKeysResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListChannelWithKeysResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ListChannelWithKeysResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/listChannelWithKeys'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> Iterable["_models.ChannelResponseList"]:
"""Returns all the Channel registrations of a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ChannelResponseList or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.ChannelResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ChannelResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ChannelResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_channels_operations.py
|
_channels_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_update_request(
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PATCH",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
channel_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
channel_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_with_keys_request(
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/listChannelWithKeys')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_resource_group_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class ChannelsOperations(object):
"""ChannelsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
parameters: "_models.BotChannel",
**kwargs: Any
) -> "_models.BotChannel":
"""Creates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.BotChannel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'BotChannel')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def update(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.Channel"] = None,
**kwargs: Any
) -> "_models.BotChannel":
"""Updates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot channel resource.
:type properties: ~azure.mgmt.botservice.models.Channel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.BotChannel(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'BotChannel')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> None:
"""Deletes a Channel registration from a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> "_models.BotChannel":
"""Returns a BotService Channel registration specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace
def list_with_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
**kwargs: Any
) -> "_models.ListChannelWithKeysResponse":
"""Lists a Channel registration for a Bot Service including secrets.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ListChannelWithKeysResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ListChannelWithKeysResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListChannelWithKeysResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ListChannelWithKeysResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/listChannelWithKeys'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> Iterable["_models.ChannelResponseList"]:
"""Returns all the Channel registrations of a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ChannelResponseList or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.ChannelResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ChannelResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ChannelResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels'} # type: ignore
| 0.77373 | 0.058346 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request(
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/hostSettings')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class HostSettingsOperations(object):
"""HostSettingsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def get(
self,
**kwargs: Any
) -> "_models.HostSettingsResponse":
"""Get per subscription settings needed to host bot in compute resource such as Azure App Service.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: HostSettingsResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.HostSettingsResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.HostSettingsResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('HostSettingsResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/hostSettings'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_host_settings_operations.py
|
_host_settings_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request(
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/hostSettings')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class HostSettingsOperations(object):
"""HostSettingsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def get(
self,
**kwargs: Any
) -> "_models.HostSettingsResponse":
"""Get per subscription settings needed to host bot in compute resource such as Azure App Service.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: HostSettingsResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.HostSettingsResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.HostSettingsResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('HostSettingsResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/hostSettings'} # type: ignore
| 0.826397 | 0.068164 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_regenerate_keys_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
channel_name: Union[str, "_models.RegenerateKeysChannelName"],
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
class DirectLineOperations(object):
"""DirectLineOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def regenerate_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.RegenerateKeysChannelName"],
parameters: "_models.SiteInfo",
**kwargs: Any
) -> "_models.BotChannel":
"""Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService
resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource for which keys are to be regenerated.
:type channel_name: str or ~azure.mgmt.botservice.models.RegenerateKeysChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.SiteInfo
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'SiteInfo')
request = build_regenerate_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
channel_name=channel_name,
content_type=content_type,
json=_json,
template_url=self.regenerate_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
regenerate_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_direct_line_operations.py
|
_direct_line_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_regenerate_keys_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
channel_name: Union[str, "_models.RegenerateKeysChannelName"],
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"channelName": _SERIALIZER.url("channel_name", channel_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
class DirectLineOperations(object):
"""DirectLineOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def regenerate_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.RegenerateKeysChannelName"],
parameters: "_models.SiteInfo",
**kwargs: Any
) -> "_models.BotChannel":
"""Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService
resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource for which keys are to be regenerated.
:type channel_name: str or ~azure.mgmt.botservice.models.RegenerateKeysChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.SiteInfo
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'SiteInfo')
request = build_regenerate_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
channel_name=channel_name,
content_type=content_type,
json=_json,
template_url=self.regenerate_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
regenerate_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys'} # type: ignore
| 0.816955 | 0.066721 |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_create_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
private_endpoint_connection_name: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class PrivateEndpointConnectionsOperations(object):
"""PrivateEndpointConnectionsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> Iterable["_models.PrivateEndpointConnectionListResult"]:
"""List all the private endpoint connections associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PrivateEndpointConnectionListResult or the result
of cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.PrivateEndpointConnectionListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Gets the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
properties: "_models.PrivateEndpointConnection",
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Update the state of specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:param properties: The private endpoint connection properties.
:type properties: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(properties, 'PrivateEndpointConnection')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> None:
"""Deletes the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_private_endpoint_connections_operations.py
|
_private_endpoint_connections_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_create_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
private_endpoint_connection_name: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class PrivateEndpointConnectionsOperations(object):
"""PrivateEndpointConnectionsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> Iterable["_models.PrivateEndpointConnectionListResult"]:
"""List all the private endpoint connections associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PrivateEndpointConnectionListResult or the result
of cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.PrivateEndpointConnectionListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Gets the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
properties: "_models.PrivateEndpointConnection",
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Update the state of specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:param properties: The private endpoint connection properties.
:type properties: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(properties, 'PrivateEndpointConnection')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> None:
"""Deletes the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
| 0.63443 | 0.053305 |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_update_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PATCH",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_resource_group_request(
resource_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_request(
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/botServices')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_check_name_availability_request(
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/providers/Microsoft.BotService/checkNameAvailability')
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
class BotsOperations(object):
"""BotsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
parameters: "_models.Bot",
**kwargs: Any
) -> "_models.Bot":
"""Creates a Bot Service. Bot Service is a resource group wide resource type.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.Bot
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'Bot')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def update(
self,
resource_group_name: str,
resource_name: str,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.BotProperties"] = None,
**kwargs: Any
) -> "_models.Bot":
"""Updates a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot resource.
:type properties: ~azure.mgmt.botservice.models.BotProperties
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.Bot(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'Bot')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> None:
"""Deletes a Bot Service from the resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.Bot":
"""Returns a BotService specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
**kwargs: Any
) -> Iterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace
def list(
self,
**kwargs: Any
) -> Iterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace
def get_check_name_availability(
self,
parameters: "_models.CheckNameAvailabilityRequestBody",
**kwargs: Any
) -> "_models.CheckNameAvailabilityResponseBody":
"""Check whether a bot name is available.
:param parameters: The request body parameters to provide for the check name availability
request.
:type parameters: ~azure.mgmt.botservice.models.CheckNameAvailabilityRequestBody
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityResponseBody, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.CheckNameAvailabilityResponseBody
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameAvailabilityResponseBody"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'CheckNameAvailabilityRequestBody')
request = build_get_check_name_availability_request(
content_type=content_type,
json=_json,
template_url=self.get_check_name_availability.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('CheckNameAvailabilityResponseBody', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_check_name_availability.metadata = {'url': '/providers/Microsoft.BotService/checkNameAvailability'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_bots_operations.py
|
_bots_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_create_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_update_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PATCH",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_resource_group_request(
resource_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_request(
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/botServices')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_check_name_availability_request(
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/providers/Microsoft.BotService/checkNameAvailability')
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
class BotsOperations(object):
"""BotsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
parameters: "_models.Bot",
**kwargs: Any
) -> "_models.Bot":
"""Creates a Bot Service. Bot Service is a resource group wide resource type.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.Bot
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'Bot')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def update(
self,
resource_group_name: str,
resource_name: str,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.BotProperties"] = None,
**kwargs: Any
) -> "_models.Bot":
"""Updates a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot resource.
:type properties: ~azure.mgmt.botservice.models.BotProperties
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.Bot(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'Bot')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> None:
"""Deletes a Bot Service from the resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.Bot":
"""Returns a BotService specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
**kwargs: Any
) -> Iterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace
def list(
self,
**kwargs: Any
) -> Iterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace
def get_check_name_availability(
self,
parameters: "_models.CheckNameAvailabilityRequestBody",
**kwargs: Any
) -> "_models.CheckNameAvailabilityResponseBody":
"""Check whether a bot name is available.
:param parameters: The request body parameters to provide for the check name availability
request.
:type parameters: ~azure.mgmt.botservice.models.CheckNameAvailabilityRequestBody
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityResponseBody, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.CheckNameAvailabilityResponseBody
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameAvailabilityResponseBody"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'CheckNameAvailabilityRequestBody')
request = build_get_check_name_availability_request(
content_type=content_type,
json=_json,
template_url=self.get_check_name_availability.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('CheckNameAvailabilityResponseBody', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_check_name_availability.metadata = {'url': '/providers/Microsoft.BotService/checkNameAvailability'} # type: ignore
| 0.686685 | 0.062789 |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_service_providers_request(
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/listAuthServiceProviders')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_with_secrets_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}/listWithSecrets')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_create_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_update_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PATCH",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_bot_service_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class BotConnectionOperations(object):
"""BotConnectionOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list_service_providers(
self,
**kwargs: Any
) -> "_models.ServiceProviderResponseList":
"""Lists the available Service Providers for creating Connection Settings.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ServiceProviderResponseList, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ServiceProviderResponseList
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceProviderResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_service_providers_request(
subscription_id=self._config.subscription_id,
template_url=self.list_service_providers.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ServiceProviderResponseList', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_service_providers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/listAuthServiceProviders'} # type: ignore
@distributed_trace
def list_with_secrets(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_secrets_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_secrets.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_secrets.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}/listWithSecrets'} # type: ignore
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Register a new Auth Connection for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for creating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def update(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Updates a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for updating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> None:
"""Deletes a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def list_by_bot_service(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> Iterable["_models.ConnectionSettingResponseList"]:
"""Returns all the Connection Settings registered to a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ConnectionSettingResponseList or the result of
cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.ConnectionSettingResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSettingResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_service.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ConnectionSettingResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_bot_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_bot_connection_operations.py
|
_bot_connection_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_service_providers_request(
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/listAuthServiceProviders')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_with_secrets_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}/listWithSecrets')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_create_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_update_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PATCH",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_get_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_delete_request(
resource_group_name: str,
resource_name: str,
connection_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"connectionName": _SERIALIZER.url("connection_name", connection_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][\sa-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_bot_service_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class BotConnectionOperations(object):
"""BotConnectionOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list_service_providers(
self,
**kwargs: Any
) -> "_models.ServiceProviderResponseList":
"""Lists the available Service Providers for creating Connection Settings.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ServiceProviderResponseList, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ServiceProviderResponseList
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceProviderResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_service_providers_request(
subscription_id=self._config.subscription_id,
template_url=self.list_service_providers.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ServiceProviderResponseList', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_service_providers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/listAuthServiceProviders'} # type: ignore
@distributed_trace
def list_with_secrets(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_secrets_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_secrets.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_secrets.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}/listWithSecrets'} # type: ignore
@distributed_trace
def create(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Register a new Auth Connection for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for creating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def update(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Updates a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for updating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def get(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def delete(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> None:
"""Deletes a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def list_by_bot_service(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> Iterable["_models.ConnectionSettingResponseList"]:
"""Returns all the Connection Settings registered to a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ConnectionSettingResponseList or the result of
cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.ConnectionSettingResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSettingResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_service.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ConnectionSettingResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_bot_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections'} # type: ignore
| 0.721841 | 0.063919 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_bot_resource_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class PrivateLinkResourcesOperations(object):
"""PrivateLinkResourcesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list_by_bot_resource(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.PrivateLinkResourceListResult":
"""Gets the private link resources that need to be created for a Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateLinkResourceListResult, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateLinkResourceListResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_by_bot_resource_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_resource.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_by_bot_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_private_link_resources_operations.py
|
_private_link_resources_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_bot_resource_request(
resource_group_name: str,
resource_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=2, pattern=r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class PrivateLinkResourcesOperations(object):
"""PrivateLinkResourcesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list_by_bot_resource(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.PrivateLinkResourceListResult":
"""Gets the private link resources that need to be created for a Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateLinkResourceListResult, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateLinkResourceListResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_by_bot_resource_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_resource.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_by_bot_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources'} # type: ignore
| 0.78016 | 0.060308 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request_initial(
subscription_id: str,
operation_result_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"operationResultId": _SERIALIZER.url("operation_result_id", operation_result_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class OperationResultsOperations(object):
"""OperationResultsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def _get_initial(
self,
operation_result_id: str,
**kwargs: Any
) -> Optional["_models.OperationResultsDescription"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationResultsDescription"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request_initial(
subscription_id=self._config.subscription_id,
operation_result_id=operation_result_id,
template_url=self._get_initial.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
@distributed_trace
def begin_get(
self,
operation_result_id: str,
**kwargs: Any
) -> LROPoller["_models.OperationResultsDescription"]:
"""Get the operation result for a long running operation.
:param operation_result_id: The ID of the operation result to get.
:type operation_result_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OperationResultsDescription or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.botservice.models.OperationResultsDescription]
:raises: ~azure.core.exceptions.HttpResponseError
"""
polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResultsDescription"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._get_initial(
operation_result_id=operation_result_id,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
def get_long_running_output(pipeline_response):
response = pipeline_response.http_response
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True: polling_method = ARMPolling(lro_delay, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_operation_results_operations.py
|
_operation_results_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request_initial(
subscription_id: str,
operation_result_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"operationResultId": _SERIALIZER.url("operation_result_id", operation_result_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class OperationResultsOperations(object):
"""OperationResultsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def _get_initial(
self,
operation_result_id: str,
**kwargs: Any
) -> Optional["_models.OperationResultsDescription"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationResultsDescription"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request_initial(
subscription_id=self._config.subscription_id,
operation_result_id=operation_result_id,
template_url=self._get_initial.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
@distributed_trace
def begin_get(
self,
operation_result_id: str,
**kwargs: Any
) -> LROPoller["_models.OperationResultsDescription"]:
"""Get the operation result for a long running operation.
:param operation_result_id: The ID of the operation result to get.
:type operation_result_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OperationResultsDescription or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.botservice.models.OperationResultsDescription]
:raises: ~azure.core.exceptions.HttpResponseError
"""
polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResultsDescription"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._get_initial(
operation_result_id=operation_result_id,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
def get_long_running_output(pipeline_response):
response = pipeline_response.http_response
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True: polling_method = ARMPolling(lro_delay, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
| 0.762778 | 0.066146 |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/providers/Microsoft.BotService/operations')
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class Operations(object):
"""Operations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
**kwargs: Any
) -> Iterable["_models.OperationEntityListResult"]:
"""Lists all the available BotService operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OperationEntityListResult or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.OperationEntityListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationEntityListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OperationEntityListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.BotService/operations'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/operations/_operations.py
|
_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(
**kwargs: Any
) -> HttpRequest:
api_version = "2021-05-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/providers/Microsoft.BotService/operations')
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class Operations(object):
"""Operations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
**kwargs: Any
) -> Iterable["_models.OperationEntityListResult"]:
"""Lists all the available BotService operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OperationEntityListResult or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.botservice.models.OperationEntityListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationEntityListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OperationEntityListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.BotService/operations'} # type: ignore
| 0.760562 | 0.075687 |
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import AzureBotServiceConfiguration
from .operations import BotConnectionOperations, BotsOperations, ChannelsOperations, DirectLineOperations, HostSettingsOperations, OperationResultsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class AzureBotService:
"""Azure Bot Service is a platform for creating smart conversational agents.
:ivar bots: BotsOperations operations
:vartype bots: azure.mgmt.botservice.aio.operations.BotsOperations
:ivar channels: ChannelsOperations operations
:vartype channels: azure.mgmt.botservice.aio.operations.ChannelsOperations
:ivar direct_line: DirectLineOperations operations
:vartype direct_line: azure.mgmt.botservice.aio.operations.DirectLineOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.botservice.aio.operations.Operations
:ivar bot_connection: BotConnectionOperations operations
:vartype bot_connection: azure.mgmt.botservice.aio.operations.BotConnectionOperations
:ivar host_settings: HostSettingsOperations operations
:vartype host_settings: azure.mgmt.botservice.aio.operations.HostSettingsOperations
:ivar operation_results: OperationResultsOperations operations
:vartype operation_results: azure.mgmt.botservice.aio.operations.OperationResultsOperations
:ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
:vartype private_endpoint_connections:
azure.mgmt.botservice.aio.operations.PrivateEndpointConnectionsOperations
:ivar private_link_resources: PrivateLinkResourcesOperations operations
:vartype private_link_resources:
azure.mgmt.botservice.aio.operations.PrivateLinkResourcesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = AzureBotServiceConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.bots = BotsOperations(self._client, self._config, self._serialize, self._deserialize)
self.channels = ChannelsOperations(self._client, self._config, self._serialize, self._deserialize)
self.direct_line = DirectLineOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.bot_connection = BotConnectionOperations(self._client, self._config, self._serialize, self._deserialize)
self.host_settings = HostSettingsOperations(self._client, self._config, self._serialize, self._deserialize)
self.operation_results = OperationResultsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "AzureBotService":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/_azure_bot_service.py
|
_azure_bot_service.py
|
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import AzureBotServiceConfiguration
from .operations import BotConnectionOperations, BotsOperations, ChannelsOperations, DirectLineOperations, HostSettingsOperations, OperationResultsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class AzureBotService:
"""Azure Bot Service is a platform for creating smart conversational agents.
:ivar bots: BotsOperations operations
:vartype bots: azure.mgmt.botservice.aio.operations.BotsOperations
:ivar channels: ChannelsOperations operations
:vartype channels: azure.mgmt.botservice.aio.operations.ChannelsOperations
:ivar direct_line: DirectLineOperations operations
:vartype direct_line: azure.mgmt.botservice.aio.operations.DirectLineOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.botservice.aio.operations.Operations
:ivar bot_connection: BotConnectionOperations operations
:vartype bot_connection: azure.mgmt.botservice.aio.operations.BotConnectionOperations
:ivar host_settings: HostSettingsOperations operations
:vartype host_settings: azure.mgmt.botservice.aio.operations.HostSettingsOperations
:ivar operation_results: OperationResultsOperations operations
:vartype operation_results: azure.mgmt.botservice.aio.operations.OperationResultsOperations
:ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
:vartype private_endpoint_connections:
azure.mgmt.botservice.aio.operations.PrivateEndpointConnectionsOperations
:ivar private_link_resources: PrivateLinkResourcesOperations operations
:vartype private_link_resources:
azure.mgmt.botservice.aio.operations.PrivateLinkResourcesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = AzureBotServiceConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.bots = BotsOperations(self._client, self._config, self._serialize, self._deserialize)
self.channels = ChannelsOperations(self._client, self._config, self._serialize, self._deserialize)
self.direct_line = DirectLineOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.bot_connection = BotConnectionOperations(self._client, self._config, self._serialize, self._deserialize)
self.host_settings = HostSettingsOperations(self._client, self._config, self._serialize, self._deserialize)
self.operation_results = OperationResultsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "AzureBotService":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
| 0.826151 | 0.101189 |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class AzureBotServiceConfiguration(Configuration):
"""Configuration for AzureBotService.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
super(AzureBotServiceConfiguration, self).__init__(**kwargs)
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = "2021-05-01-preview"
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'mgmt-botservice/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs: Any
) -> None:
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/_configuration.py
|
_configuration.py
|
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class AzureBotServiceConfiguration(Configuration):
"""Configuration for AzureBotService.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID.
:type subscription_id: str
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
super(AzureBotServiceConfiguration, self).__init__(**kwargs)
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = "2021-05-01-preview"
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'mgmt-botservice/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs: Any
) -> None:
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
| 0.821474 | 0.073497 |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._channels_operations import build_create_request, build_delete_request, build_get_request, build_list_by_resource_group_request, build_list_with_keys_request, build_update_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ChannelsOperations:
"""ChannelsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
parameters: "_models.BotChannel",
**kwargs: Any
) -> "_models.BotChannel":
"""Creates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.BotChannel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'BotChannel')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def update(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.Channel"] = None,
**kwargs: Any
) -> "_models.BotChannel":
"""Updates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot channel resource.
:type properties: ~azure.mgmt.botservice.models.Channel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.BotChannel(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'BotChannel')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> None:
"""Deletes a Channel registration from a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> "_models.BotChannel":
"""Returns a BotService Channel registration specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def list_with_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
**kwargs: Any
) -> "_models.ListChannelWithKeysResponse":
"""Lists a Channel registration for a Bot Service including secrets.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ListChannelWithKeysResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ListChannelWithKeysResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListChannelWithKeysResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ListChannelWithKeysResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/listChannelWithKeys'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> AsyncIterable["_models.ChannelResponseList"]:
"""Returns all the Channel registrations of a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ChannelResponseList or the result of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.ChannelResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ChannelResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ChannelResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_channels_operations.py
|
_channels_operations.py
|
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._channels_operations import build_create_request, build_delete_request, build_get_request, build_list_by_resource_group_request, build_list_with_keys_request, build_update_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ChannelsOperations:
"""ChannelsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
parameters: "_models.BotChannel",
**kwargs: Any
) -> "_models.BotChannel":
"""Creates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.BotChannel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'BotChannel')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def update(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.Channel"] = None,
**kwargs: Any
) -> "_models.BotChannel":
"""Updates a Channel registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot channel resource.
:type properties: ~azure.mgmt.botservice.models.Channel
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.BotChannel(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'BotChannel')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BotChannel', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> None:
"""Deletes a Channel registration from a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
channel_name: str,
**kwargs: Any
) -> "_models.BotChannel":
"""Returns a BotService Channel registration specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Bot resource.
:type channel_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}'} # type: ignore
@distributed_trace_async
async def list_with_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.ChannelName"],
**kwargs: Any
) -> "_models.ListChannelWithKeysResponse":
"""Lists a Channel registration for a Bot Service including secrets.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource.
:type channel_name: str or ~azure.mgmt.botservice.models.ChannelName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ListChannelWithKeysResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ListChannelWithKeysResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListChannelWithKeysResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
channel_name=channel_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ListChannelWithKeysResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/listChannelWithKeys'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> AsyncIterable["_models.ChannelResponseList"]:
"""Returns all the Channel registrations of a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ChannelResponseList or the result of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.ChannelResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ChannelResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ChannelResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels'} # type: ignore
| 0.868158 | 0.094552 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._host_settings_operations import build_get_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class HostSettingsOperations:
"""HostSettingsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def get(
self,
**kwargs: Any
) -> "_models.HostSettingsResponse":
"""Get per subscription settings needed to host bot in compute resource such as Azure App Service.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: HostSettingsResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.HostSettingsResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.HostSettingsResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('HostSettingsResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/hostSettings'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_host_settings_operations.py
|
_host_settings_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._host_settings_operations import build_get_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class HostSettingsOperations:
"""HostSettingsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def get(
self,
**kwargs: Any
) -> "_models.HostSettingsResponse":
"""Get per subscription settings needed to host bot in compute resource such as Azure App Service.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: HostSettingsResponse, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.HostSettingsResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.HostSettingsResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('HostSettingsResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/hostSettings'} # type: ignore
| 0.848784 | 0.076822 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._direct_line_operations import build_regenerate_keys_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class DirectLineOperations:
"""DirectLineOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def regenerate_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.RegenerateKeysChannelName"],
parameters: "_models.SiteInfo",
**kwargs: Any
) -> "_models.BotChannel":
"""Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService
resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource for which keys are to be regenerated.
:type channel_name: str or ~azure.mgmt.botservice.models.RegenerateKeysChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.SiteInfo
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'SiteInfo')
request = build_regenerate_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
channel_name=channel_name,
content_type=content_type,
json=_json,
template_url=self.regenerate_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
regenerate_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_direct_line_operations.py
|
_direct_line_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._direct_line_operations import build_regenerate_keys_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class DirectLineOperations:
"""DirectLineOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def regenerate_keys(
self,
resource_group_name: str,
resource_name: str,
channel_name: Union[str, "_models.RegenerateKeysChannelName"],
parameters: "_models.SiteInfo",
**kwargs: Any
) -> "_models.BotChannel":
"""Regenerates secret keys and returns them for the DirectLine Channel of a particular BotService
resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param channel_name: The name of the Channel resource for which keys are to be regenerated.
:type channel_name: str or ~azure.mgmt.botservice.models.RegenerateKeysChannelName
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.SiteInfo
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BotChannel, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.BotChannel
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotChannel"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'SiteInfo')
request = build_regenerate_keys_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
channel_name=channel_name,
content_type=content_type,
json=_json,
template_url=self.regenerate_keys.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('BotChannel', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
regenerate_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/channels/{channelName}/regeneratekeys'} # type: ignore
| 0.855459 | 0.092237 |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._private_endpoint_connections_operations import build_create_request, build_delete_request, build_get_request, build_list_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class PrivateEndpointConnectionsOperations:
"""PrivateEndpointConnectionsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> AsyncIterable["_models.PrivateEndpointConnectionListResult"]:
"""List all the private endpoint connections associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PrivateEndpointConnectionListResult or the result
of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.PrivateEndpointConnectionListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Gets the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
properties: "_models.PrivateEndpointConnection",
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Update the state of specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:param properties: The private endpoint connection properties.
:type properties: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(properties, 'PrivateEndpointConnection')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> None:
"""Deletes the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_private_endpoint_connections_operations.py
|
_private_endpoint_connections_operations.py
|
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._private_endpoint_connections_operations import build_create_request, build_delete_request, build_get_request, build_list_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class PrivateEndpointConnectionsOperations:
"""PrivateEndpointConnectionsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> AsyncIterable["_models.PrivateEndpointConnectionListResult"]:
"""List all the private endpoint connections associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PrivateEndpointConnectionListResult or the result
of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.PrivateEndpointConnectionListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Gets the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
properties: "_models.PrivateEndpointConnection",
**kwargs: Any
) -> "_models.PrivateEndpointConnection":
"""Update the state of specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:param properties: The private endpoint connection properties.
:type properties: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateEndpointConnection, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateEndpointConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(properties, 'PrivateEndpointConnection')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
private_endpoint_connection_name: str,
**kwargs: Any
) -> None:
"""Deletes the specified private endpoint connection associated with the Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param private_endpoint_connection_name: The name of the private endpoint connection associated
with the Azure resource.
:type private_endpoint_connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
private_endpoint_connection_name=private_endpoint_connection_name,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
| 0.806586 | 0.076961 |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._bots_operations import build_create_request, build_delete_request, build_get_check_name_availability_request, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class BotsOperations:
"""BotsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
parameters: "_models.Bot",
**kwargs: Any
) -> "_models.Bot":
"""Creates a Bot Service. Bot Service is a resource group wide resource type.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.Bot
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'Bot')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace_async
async def update(
self,
resource_group_name: str,
resource_name: str,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.BotProperties"] = None,
**kwargs: Any
) -> "_models.Bot":
"""Updates a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot resource.
:type properties: ~azure.mgmt.botservice.models.BotProperties
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.Bot(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'Bot')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> None:
"""Deletes a Bot Service from the resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.Bot":
"""Returns a BotService specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
**kwargs: Any
) -> AsyncIterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace
def list(
self,
**kwargs: Any
) -> AsyncIterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace_async
async def get_check_name_availability(
self,
parameters: "_models.CheckNameAvailabilityRequestBody",
**kwargs: Any
) -> "_models.CheckNameAvailabilityResponseBody":
"""Check whether a bot name is available.
:param parameters: The request body parameters to provide for the check name availability
request.
:type parameters: ~azure.mgmt.botservice.models.CheckNameAvailabilityRequestBody
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityResponseBody, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.CheckNameAvailabilityResponseBody
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameAvailabilityResponseBody"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'CheckNameAvailabilityRequestBody')
request = build_get_check_name_availability_request(
content_type=content_type,
json=_json,
template_url=self.get_check_name_availability.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('CheckNameAvailabilityResponseBody', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_check_name_availability.metadata = {'url': '/providers/Microsoft.BotService/checkNameAvailability'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_bots_operations.py
|
_bots_operations.py
|
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._bots_operations import build_create_request, build_delete_request, build_get_check_name_availability_request, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class BotsOperations:
"""BotsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
parameters: "_models.Bot",
**kwargs: Any
) -> "_models.Bot":
"""Creates a Bot Service. Bot Service is a resource group wide resource type.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param parameters: The parameters to provide for the created bot.
:type parameters: ~azure.mgmt.botservice.models.Bot
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'Bot')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace_async
async def update(
self,
resource_group_name: str,
resource_name: str,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["_models.Sku"] = None,
kind: Optional[Union[str, "_models.Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["_models.BotProperties"] = None,
**kwargs: Any
) -> "_models.Bot":
"""Updates a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param location: Specifies the location of the resource.
:type location: str
:param tags: Contains resource tags defined as key/value pairs.
:type tags: dict[str, str]
:param sku: Gets or sets the SKU of the resource.
:type sku: ~azure.mgmt.botservice.models.Sku
:param kind: Required. Gets or sets the Kind of the resource.
:type kind: str or ~azure.mgmt.botservice.models.Kind
:param etag: Entity Tag.
:type etag: str
:param properties: The set of properties specific to bot resource.
:type properties: ~azure.mgmt.botservice.models.BotProperties
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_parameters = _models.Bot(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties)
_json = self._serialize.body(_parameters, 'Bot')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Bot', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> None:
"""Deletes a Bot Service from the resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.Bot":
"""Returns a BotService specified by the parameters.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Bot, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.Bot
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.Bot"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('Bot', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}'} # type: ignore
@distributed_trace
def list_by_resource_group(
self,
resource_group_name: str,
**kwargs: Any
) -> AsyncIterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a resource group.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace
def list(
self,
**kwargs: Any
) -> AsyncIterable["_models.BotResponseList"]:
"""Returns all the resources of a particular type belonging to a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either BotResponseList or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.BotResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BotResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("BotResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/botServices'} # type: ignore
@distributed_trace_async
async def get_check_name_availability(
self,
parameters: "_models.CheckNameAvailabilityRequestBody",
**kwargs: Any
) -> "_models.CheckNameAvailabilityResponseBody":
"""Check whether a bot name is available.
:param parameters: The request body parameters to provide for the check name availability
request.
:type parameters: ~azure.mgmt.botservice.models.CheckNameAvailabilityRequestBody
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityResponseBody, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.CheckNameAvailabilityResponseBody
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameAvailabilityResponseBody"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'CheckNameAvailabilityRequestBody')
request = build_get_check_name_availability_request(
content_type=content_type,
json=_json,
template_url=self.get_check_name_availability.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('CheckNameAvailabilityResponseBody', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_check_name_availability.metadata = {'url': '/providers/Microsoft.BotService/checkNameAvailability'} # type: ignore
| 0.842118 | 0.099426 |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._bot_connection_operations import build_create_request, build_delete_request, build_get_request, build_list_by_bot_service_request, build_list_service_providers_request, build_list_with_secrets_request, build_update_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class BotConnectionOperations:
"""BotConnectionOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def list_service_providers(
self,
**kwargs: Any
) -> "_models.ServiceProviderResponseList":
"""Lists the available Service Providers for creating Connection Settings.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ServiceProviderResponseList, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ServiceProviderResponseList
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceProviderResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_service_providers_request(
subscription_id=self._config.subscription_id,
template_url=self.list_service_providers.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ServiceProviderResponseList', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_service_providers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/listAuthServiceProviders'} # type: ignore
@distributed_trace_async
async def list_with_secrets(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_secrets_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_secrets.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_secrets.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}/listWithSecrets'} # type: ignore
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Register a new Auth Connection for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for creating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace_async
async def update(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Updates a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for updating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> None:
"""Deletes a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def list_by_bot_service(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> AsyncIterable["_models.ConnectionSettingResponseList"]:
"""Returns all the Connection Settings registered to a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ConnectionSettingResponseList or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.ConnectionSettingResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSettingResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_service.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ConnectionSettingResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_bot_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_bot_connection_operations.py
|
_bot_connection_operations.py
|
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._bot_connection_operations import build_create_request, build_delete_request, build_get_request, build_list_by_bot_service_request, build_list_service_providers_request, build_list_with_secrets_request, build_update_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class BotConnectionOperations:
"""BotConnectionOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def list_service_providers(
self,
**kwargs: Any
) -> "_models.ServiceProviderResponseList":
"""Lists the available Service Providers for creating Connection Settings.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ServiceProviderResponseList, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ServiceProviderResponseList
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ServiceProviderResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_service_providers_request(
subscription_id=self._config.subscription_id,
template_url=self.list_service_providers.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ServiceProviderResponseList', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_service_providers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/listAuthServiceProviders'} # type: ignore
@distributed_trace_async
async def list_with_secrets(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_with_secrets_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.list_with_secrets.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_with_secrets.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}/listWithSecrets'} # type: ignore
@distributed_trace_async
async def create(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Register a new Auth Connection for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for creating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_create_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace_async
async def update(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
parameters: "_models.ConnectionSetting",
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Updates a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:param parameters: The parameters to provide for updating the Connection Setting.
:type parameters: ~azure.mgmt.botservice.models.ConnectionSetting
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'ConnectionSetting')
request = build_update_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
template_url=self.update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.ConnectionSetting":
"""Get a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ConnectionSetting, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.ConnectionSetting
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSetting"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('ConnectionSetting', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
resource_name: str,
connection_name: str,
**kwargs: Any
) -> None:
"""Deletes a Connection Setting registration for a Bot Service.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:param connection_name: The name of the Bot Service Connection Setting resource.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
connection_name=connection_name,
subscription_id=self._config.subscription_id,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections/{connectionName}'} # type: ignore
@distributed_trace
def list_by_bot_service(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> AsyncIterable["_models.ConnectionSettingResponseList"]:
"""Returns all the Connection Settings registered to a particular BotService resource.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ConnectionSettingResponseList or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.ConnectionSettingResponseList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSettingResponseList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_service.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_bot_service_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ConnectionSettingResponseList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_bot_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/connections'} # type: ignore
| 0.797911 | 0.076996 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._private_link_resources_operations import build_list_by_bot_resource_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class PrivateLinkResourcesOperations:
"""PrivateLinkResourcesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def list_by_bot_resource(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.PrivateLinkResourceListResult":
"""Gets the private link resources that need to be created for a Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateLinkResourceListResult, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateLinkResourceListResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_by_bot_resource_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_resource.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_by_bot_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_private_link_resources_operations.py
|
_private_link_resources_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._private_link_resources_operations import build_list_by_bot_resource_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class PrivateLinkResourcesOperations:
"""PrivateLinkResourcesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace_async
async def list_by_bot_resource(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.PrivateLinkResourceListResult":
"""Gets the private link resources that need to be created for a Bot.
:param resource_group_name: The name of the Bot resource group in the user subscription.
:type resource_group_name: str
:param resource_name: The name of the Bot resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateLinkResourceListResult, or the result of cls(response)
:rtype: ~azure.mgmt.botservice.models.PrivateLinkResourceListResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_list_by_bot_resource_request(
resource_group_name=resource_group_name,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
template_url=self.list_by_bot_resource.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_by_bot_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BotService/botServices/{resourceName}/privateLinkResources'} # type: ignore
| 0.849066 | 0.07343 |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operation_results_operations import build_get_request_initial
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class OperationResultsOperations:
"""OperationResultsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _get_initial(
self,
operation_result_id: str,
**kwargs: Any
) -> Optional["_models.OperationResultsDescription"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationResultsDescription"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request_initial(
subscription_id=self._config.subscription_id,
operation_result_id=operation_result_id,
template_url=self._get_initial.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
@distributed_trace_async
async def begin_get(
self,
operation_result_id: str,
**kwargs: Any
) -> AsyncLROPoller["_models.OperationResultsDescription"]:
"""Get the operation result for a long running operation.
:param operation_result_id: The ID of the operation result to get.
:type operation_result_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationResultsDescription or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.botservice.models.OperationResultsDescription]
:raises: ~azure.core.exceptions.HttpResponseError
"""
polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResultsDescription"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._get_initial(
operation_result_id=operation_result_id,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
def get_long_running_output(pipeline_response):
response = pipeline_response.http_response
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_operation_results_operations.py
|
_operation_results_operations.py
|
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operation_results_operations import build_get_request_initial
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class OperationResultsOperations:
"""OperationResultsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _get_initial(
self,
operation_result_id: str,
**kwargs: Any
) -> Optional["_models.OperationResultsDescription"]:
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationResultsDescription"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request_initial(
subscription_id=self._config.subscription_id,
operation_result_id=operation_result_id,
template_url=self._get_initial.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_get_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
@distributed_trace_async
async def begin_get(
self,
operation_result_id: str,
**kwargs: Any
) -> AsyncLROPoller["_models.OperationResultsDescription"]:
"""Get the operation result for a long running operation.
:param operation_result_id: The ID of the operation result to get.
:type operation_result_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OperationResultsDescription or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.botservice.models.OperationResultsDescription]
:raises: ~azure.core.exceptions.HttpResponseError
"""
polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResultsDescription"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._get_initial(
operation_result_id=operation_result_id,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
def get_long_running_output(pipeline_response):
response = pipeline_response.http_response
deserialized = self._deserialize('OperationResultsDescription', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.BotService/operationresults/{operationResultId}'} # type: ignore
| 0.810179 | 0.092934 |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operations import build_list_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""Operations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
**kwargs: Any
) -> AsyncIterable["_models.OperationEntityListResult"]:
"""Lists all the available BotService operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OperationEntityListResult or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.OperationEntityListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationEntityListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OperationEntityListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.BotService/operations'} # type: ignore
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/aio/operations/_operations.py
|
_operations.py
|
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operations import build_list_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""Operations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.botservice.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
**kwargs: Any
) -> AsyncIterable["_models.OperationEntityListResult"]:
"""Lists all the available BotService operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OperationEntityListResult or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.botservice.models.OperationEntityListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationEntityListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OperationEntityListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/providers/Microsoft.BotService/operations'} # type: ignore
| 0.799325 | 0.088387 |
from typing import Any, Dict, List, Optional, Union
from azure.core.exceptions import HttpResponseError
import msrest.serialization
from ._azure_bot_service_enums import *
class Channel(msrest.serialization.Model):
"""Channel definition.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: AlexaChannel, DirectLineChannel, DirectLineSpeechChannel, EmailChannel, FacebookChannel, KikChannel, LineChannel, MsTeamsChannel, SkypeChannel, SlackChannel, SmsChannel, TelegramChannel, WebChatChannel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
}
_subtype_map = {
'channel_name': {'AlexaChannel': 'AlexaChannel', 'DirectLineChannel': 'DirectLineChannel', 'DirectLineSpeechChannel': 'DirectLineSpeechChannel', 'EmailChannel': 'EmailChannel', 'FacebookChannel': 'FacebookChannel', 'KikChannel': 'KikChannel', 'LineChannel': 'LineChannel', 'MsTeamsChannel': 'MsTeamsChannel', 'SkypeChannel': 'SkypeChannel', 'SlackChannel': 'SlackChannel', 'SmsChannel': 'SmsChannel', 'TelegramChannel': 'TelegramChannel', 'WebChatChannel': 'WebChatChannel'}
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
"""
super(Channel, self).__init__(**kwargs)
self.channel_name = None # type: Optional[str]
self.etag = etag
self.provisioning_state = None
self.location = location
class AlexaChannel(Channel):
"""Alexa channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Alexa channel resource.
:vartype properties: ~azure.mgmt.botservice.models.AlexaChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'AlexaChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["AlexaChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Alexa channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.AlexaChannelProperties
"""
super(AlexaChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'AlexaChannel' # type: str
self.properties = properties
class AlexaChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Alexa channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar alexa_skill_id: Required. The Alexa skill Id.
:vartype alexa_skill_id: str
:ivar url_fragment: Url fragment used in part of the Uri configured in Alexa.
:vartype url_fragment: str
:ivar service_endpoint_uri: Full Uri used to configured the skill in Alexa.
:vartype service_endpoint_uri: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'alexa_skill_id': {'required': True},
'url_fragment': {'readonly': True},
'service_endpoint_uri': {'readonly': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'alexa_skill_id': {'key': 'alexaSkillId', 'type': 'str'},
'url_fragment': {'key': 'urlFragment', 'type': 'str'},
'service_endpoint_uri': {'key': 'serviceEndpointUri', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
alexa_skill_id: str,
is_enabled: bool,
**kwargs
):
"""
:keyword alexa_skill_id: Required. The Alexa skill Id.
:paramtype alexa_skill_id: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(AlexaChannelProperties, self).__init__(**kwargs)
self.alexa_skill_id = alexa_skill_id
self.url_fragment = None
self.service_endpoint_uri = None
self.is_enabled = is_enabled
class Resource(msrest.serialization.Model):
"""Azure resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
"""
super(Resource, self).__init__(**kwargs)
self.id = None
self.name = None
self.location = location
self.type = None
self.tags = tags
self.sku = sku
self.kind = kind
self.etag = etag
self.zones = None
class Bot(Resource):
"""Bot resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot resource.
:vartype properties: ~azure.mgmt.botservice.models.BotProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'BotProperties'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["BotProperties"] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot resource.
:paramtype properties: ~azure.mgmt.botservice.models.BotProperties
"""
super(Bot, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, **kwargs)
self.properties = properties
class BotChannel(Resource):
"""Bot channel resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot channel resource.
:vartype properties: ~azure.mgmt.botservice.models.Channel
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'Channel'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["Channel"] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.Channel
"""
super(BotChannel, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, **kwargs)
self.properties = properties
class BotProperties(msrest.serialization.Model):
"""The parameters to provide for the Bot.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar display_name: Required. The Name of the bot.
:vartype display_name: str
:ivar description: The description of the bot.
:vartype description: str
:ivar icon_url: The Icon Url of the bot.
:vartype icon_url: str
:ivar endpoint: Required. The bot's endpoint.
:vartype endpoint: str
:ivar endpoint_version: The bot's endpoint version.
:vartype endpoint_version: str
:ivar all_settings: Contains resource all settings defined as key/value pairs.
:vartype all_settings: dict[str, str]
:ivar parameters: Contains resource parameters defined as key/value pairs.
:vartype parameters: dict[str, str]
:ivar manifest_url: The bot's manifest url.
:vartype manifest_url: str
:ivar msa_app_type: Microsoft App Type for the bot. Possible values include: "UserAssignedMSI",
"SingleTenant", "MultiTenant".
:vartype msa_app_type: str or ~azure.mgmt.botservice.models.MsaAppType
:ivar msa_app_id: Required. Microsoft App Id for the bot.
:vartype msa_app_id: str
:ivar msa_app_tenant_id: Microsoft App Tenant Id for the bot.
:vartype msa_app_tenant_id: str
:ivar msa_app_msi_resource_id: Microsoft App Managed Identity Resource Id for the bot.
:vartype msa_app_msi_resource_id: str
:ivar configured_channels: Collection of channels for which the bot is configured.
:vartype configured_channels: list[str]
:ivar enabled_channels: Collection of channels for which the bot is enabled.
:vartype enabled_channels: list[str]
:ivar developer_app_insight_key: The Application Insights key.
:vartype developer_app_insight_key: str
:ivar developer_app_insights_api_key: The Application Insights Api Key.
:vartype developer_app_insights_api_key: str
:ivar developer_app_insights_application_id: The Application Insights App Id.
:vartype developer_app_insights_application_id: str
:ivar luis_app_ids: Collection of LUIS App Ids.
:vartype luis_app_ids: list[str]
:ivar luis_key: The LUIS Key.
:vartype luis_key: str
:ivar is_cmek_enabled: Whether Cmek is enabled.
:vartype is_cmek_enabled: bool
:ivar cmek_key_vault_url: The CMK Url.
:vartype cmek_key_vault_url: str
:ivar cmek_encryption_status: The CMK encryption status.
:vartype cmek_encryption_status: str
:ivar public_network_access: Whether the bot is in an isolated network. Possible values
include: "Enabled", "Disabled". Default value: "Enabled".
:vartype public_network_access: str or ~azure.mgmt.botservice.models.PublicNetworkAccess
:ivar is_streaming_supported: Whether the bot is streaming supported.
:vartype is_streaming_supported: bool
:ivar is_developer_app_insights_api_key_set: Whether the bot is developerAppInsightsApiKey set.
:vartype is_developer_app_insights_api_key_set: bool
:ivar migration_token: Token used to migrate non Azure bot to azure subscription.
:vartype migration_token: str
:ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:vartype disable_local_auth: bool
:ivar schema_transformation_version: The channel schema transformation version for the bot.
:vartype schema_transformation_version: str
:ivar storage_resource_id: The storage resourceId for the bot.
:vartype storage_resource_id: str
:ivar private_endpoint_connections: List of Private Endpoint Connections configured for the
bot.
:vartype private_endpoint_connections:
list[~azure.mgmt.botservice.models.PrivateEndpointConnection]
:ivar open_with_hint: The hint to browser (e.g. protocol handler) on how to open the bot for
authoring.
:vartype open_with_hint: str
:ivar app_password_hint: The hint (e.g. keyVault secret resourceId) on how to fetch the app
secret.
:vartype app_password_hint: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar publishing_credentials: Publishing credentials of the resource.
:vartype publishing_credentials: str
"""
_validation = {
'display_name': {'required': True},
'endpoint': {'required': True},
'endpoint_version': {'readonly': True},
'msa_app_id': {'required': True},
'configured_channels': {'readonly': True},
'enabled_channels': {'readonly': True},
'cmek_encryption_status': {'readonly': True},
'is_developer_app_insights_api_key_set': {'readonly': True},
'migration_token': {'readonly': True},
'private_endpoint_connections': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'icon_url': {'key': 'iconUrl', 'type': 'str'},
'endpoint': {'key': 'endpoint', 'type': 'str'},
'endpoint_version': {'key': 'endpointVersion', 'type': 'str'},
'all_settings': {'key': 'allSettings', 'type': '{str}'},
'parameters': {'key': 'parameters', 'type': '{str}'},
'manifest_url': {'key': 'manifestUrl', 'type': 'str'},
'msa_app_type': {'key': 'msaAppType', 'type': 'str'},
'msa_app_id': {'key': 'msaAppId', 'type': 'str'},
'msa_app_tenant_id': {'key': 'msaAppTenantId', 'type': 'str'},
'msa_app_msi_resource_id': {'key': 'msaAppMSIResourceId', 'type': 'str'},
'configured_channels': {'key': 'configuredChannels', 'type': '[str]'},
'enabled_channels': {'key': 'enabledChannels', 'type': '[str]'},
'developer_app_insight_key': {'key': 'developerAppInsightKey', 'type': 'str'},
'developer_app_insights_api_key': {'key': 'developerAppInsightsApiKey', 'type': 'str'},
'developer_app_insights_application_id': {'key': 'developerAppInsightsApplicationId', 'type': 'str'},
'luis_app_ids': {'key': 'luisAppIds', 'type': '[str]'},
'luis_key': {'key': 'luisKey', 'type': 'str'},
'is_cmek_enabled': {'key': 'isCmekEnabled', 'type': 'bool'},
'cmek_key_vault_url': {'key': 'cmekKeyVaultUrl', 'type': 'str'},
'cmek_encryption_status': {'key': 'cmekEncryptionStatus', 'type': 'str'},
'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'},
'is_streaming_supported': {'key': 'isStreamingSupported', 'type': 'bool'},
'is_developer_app_insights_api_key_set': {'key': 'isDeveloperAppInsightsApiKeySet', 'type': 'bool'},
'migration_token': {'key': 'migrationToken', 'type': 'str'},
'disable_local_auth': {'key': 'disableLocalAuth', 'type': 'bool'},
'schema_transformation_version': {'key': 'schemaTransformationVersion', 'type': 'str'},
'storage_resource_id': {'key': 'storageResourceId', 'type': 'str'},
'private_endpoint_connections': {'key': 'privateEndpointConnections', 'type': '[PrivateEndpointConnection]'},
'open_with_hint': {'key': 'openWithHint', 'type': 'str'},
'app_password_hint': {'key': 'appPasswordHint', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'publishing_credentials': {'key': 'publishingCredentials', 'type': 'str'},
}
def __init__(
self,
*,
display_name: str,
endpoint: str,
msa_app_id: str,
description: Optional[str] = None,
icon_url: Optional[str] = None,
all_settings: Optional[Dict[str, str]] = None,
parameters: Optional[Dict[str, str]] = None,
manifest_url: Optional[str] = None,
msa_app_type: Optional[Union[str, "MsaAppType"]] = None,
msa_app_tenant_id: Optional[str] = None,
msa_app_msi_resource_id: Optional[str] = None,
developer_app_insight_key: Optional[str] = None,
developer_app_insights_api_key: Optional[str] = None,
developer_app_insights_application_id: Optional[str] = None,
luis_app_ids: Optional[List[str]] = None,
luis_key: Optional[str] = None,
is_cmek_enabled: Optional[bool] = None,
cmek_key_vault_url: Optional[str] = None,
public_network_access: Optional[Union[str, "PublicNetworkAccess"]] = "Enabled",
is_streaming_supported: Optional[bool] = False,
disable_local_auth: Optional[bool] = None,
schema_transformation_version: Optional[str] = None,
storage_resource_id: Optional[str] = None,
open_with_hint: Optional[str] = None,
app_password_hint: Optional[str] = None,
publishing_credentials: Optional[str] = None,
**kwargs
):
"""
:keyword display_name: Required. The Name of the bot.
:paramtype display_name: str
:keyword description: The description of the bot.
:paramtype description: str
:keyword icon_url: The Icon Url of the bot.
:paramtype icon_url: str
:keyword endpoint: Required. The bot's endpoint.
:paramtype endpoint: str
:keyword all_settings: Contains resource all settings defined as key/value pairs.
:paramtype all_settings: dict[str, str]
:keyword parameters: Contains resource parameters defined as key/value pairs.
:paramtype parameters: dict[str, str]
:keyword manifest_url: The bot's manifest url.
:paramtype manifest_url: str
:keyword msa_app_type: Microsoft App Type for the bot. Possible values include:
"UserAssignedMSI", "SingleTenant", "MultiTenant".
:paramtype msa_app_type: str or ~azure.mgmt.botservice.models.MsaAppType
:keyword msa_app_id: Required. Microsoft App Id for the bot.
:paramtype msa_app_id: str
:keyword msa_app_tenant_id: Microsoft App Tenant Id for the bot.
:paramtype msa_app_tenant_id: str
:keyword msa_app_msi_resource_id: Microsoft App Managed Identity Resource Id for the bot.
:paramtype msa_app_msi_resource_id: str
:keyword developer_app_insight_key: The Application Insights key.
:paramtype developer_app_insight_key: str
:keyword developer_app_insights_api_key: The Application Insights Api Key.
:paramtype developer_app_insights_api_key: str
:keyword developer_app_insights_application_id: The Application Insights App Id.
:paramtype developer_app_insights_application_id: str
:keyword luis_app_ids: Collection of LUIS App Ids.
:paramtype luis_app_ids: list[str]
:keyword luis_key: The LUIS Key.
:paramtype luis_key: str
:keyword is_cmek_enabled: Whether Cmek is enabled.
:paramtype is_cmek_enabled: bool
:keyword cmek_key_vault_url: The CMK Url.
:paramtype cmek_key_vault_url: str
:keyword public_network_access: Whether the bot is in an isolated network. Possible values
include: "Enabled", "Disabled". Default value: "Enabled".
:paramtype public_network_access: str or ~azure.mgmt.botservice.models.PublicNetworkAccess
:keyword is_streaming_supported: Whether the bot is streaming supported.
:paramtype is_streaming_supported: bool
:keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:paramtype disable_local_auth: bool
:keyword schema_transformation_version: The channel schema transformation version for the bot.
:paramtype schema_transformation_version: str
:keyword storage_resource_id: The storage resourceId for the bot.
:paramtype storage_resource_id: str
:keyword open_with_hint: The hint to browser (e.g. protocol handler) on how to open the bot for
authoring.
:paramtype open_with_hint: str
:keyword app_password_hint: The hint (e.g. keyVault secret resourceId) on how to fetch the app
secret.
:paramtype app_password_hint: str
:keyword publishing_credentials: Publishing credentials of the resource.
:paramtype publishing_credentials: str
"""
super(BotProperties, self).__init__(**kwargs)
self.display_name = display_name
self.description = description
self.icon_url = icon_url
self.endpoint = endpoint
self.endpoint_version = None
self.all_settings = all_settings
self.parameters = parameters
self.manifest_url = manifest_url
self.msa_app_type = msa_app_type
self.msa_app_id = msa_app_id
self.msa_app_tenant_id = msa_app_tenant_id
self.msa_app_msi_resource_id = msa_app_msi_resource_id
self.configured_channels = None
self.enabled_channels = None
self.developer_app_insight_key = developer_app_insight_key
self.developer_app_insights_api_key = developer_app_insights_api_key
self.developer_app_insights_application_id = developer_app_insights_application_id
self.luis_app_ids = luis_app_ids
self.luis_key = luis_key
self.is_cmek_enabled = is_cmek_enabled
self.cmek_key_vault_url = cmek_key_vault_url
self.cmek_encryption_status = None
self.public_network_access = public_network_access
self.is_streaming_supported = is_streaming_supported
self.is_developer_app_insights_api_key_set = None
self.migration_token = None
self.disable_local_auth = disable_local_auth
self.schema_transformation_version = schema_transformation_version
self.storage_resource_id = storage_resource_id
self.private_endpoint_connections = None
self.open_with_hint = open_with_hint
self.app_password_hint = app_password_hint
self.provisioning_state = None
self.publishing_credentials = publishing_credentials
class BotResponseList(msrest.serialization.Model):
"""The list of bot service operation response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service resources.
:vartype next_link: str
:ivar value: Gets the list of bot service results and their properties.
:vartype value: list[~azure.mgmt.botservice.models.Bot]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[Bot]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service resources.
:paramtype next_link: str
"""
super(BotResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class ChannelResponseList(msrest.serialization.Model):
"""The list of bot service channel operation response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service channel resources.
:vartype next_link: str
:ivar value: Gets the list of bot service channel results and their properties.
:vartype value: list[~azure.mgmt.botservice.models.BotChannel]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[BotChannel]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service channel resources.
:paramtype next_link: str
"""
super(ChannelResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class ChannelSettings(msrest.serialization.Model):
"""Channel settings definition.
:ivar extension_key1: The extensionKey1.
:vartype extension_key1: str
:ivar extension_key2: The extensionKey2.
:vartype extension_key2: str
:ivar sites: The list of sites.
:vartype sites: list[~azure.mgmt.botservice.models.Site]
:ivar channel_id: The channel id.
:vartype channel_id: str
:ivar channel_display_name: The channel display name.
:vartype channel_display_name: str
:ivar bot_id: The bot id.
:vartype bot_id: str
:ivar bot_icon_url: The bot icon url.
:vartype bot_icon_url: str
:ivar is_enabled: Whether this channel is enabled for the bot.
:vartype is_enabled: bool
:ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:vartype disable_local_auth: bool
"""
_attribute_map = {
'extension_key1': {'key': 'extensionKey1', 'type': 'str'},
'extension_key2': {'key': 'extensionKey2', 'type': 'str'},
'sites': {'key': 'sites', 'type': '[Site]'},
'channel_id': {'key': 'channelId', 'type': 'str'},
'channel_display_name': {'key': 'channelDisplayName', 'type': 'str'},
'bot_id': {'key': 'botId', 'type': 'str'},
'bot_icon_url': {'key': 'botIconUrl', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'disable_local_auth': {'key': 'disableLocalAuth', 'type': 'bool'},
}
def __init__(
self,
*,
extension_key1: Optional[str] = None,
extension_key2: Optional[str] = None,
sites: Optional[List["Site"]] = None,
channel_id: Optional[str] = None,
channel_display_name: Optional[str] = None,
bot_id: Optional[str] = None,
bot_icon_url: Optional[str] = None,
is_enabled: Optional[bool] = None,
disable_local_auth: Optional[bool] = None,
**kwargs
):
"""
:keyword extension_key1: The extensionKey1.
:paramtype extension_key1: str
:keyword extension_key2: The extensionKey2.
:paramtype extension_key2: str
:keyword sites: The list of sites.
:paramtype sites: list[~azure.mgmt.botservice.models.Site]
:keyword channel_id: The channel id.
:paramtype channel_id: str
:keyword channel_display_name: The channel display name.
:paramtype channel_display_name: str
:keyword bot_id: The bot id.
:paramtype bot_id: str
:keyword bot_icon_url: The bot icon url.
:paramtype bot_icon_url: str
:keyword is_enabled: Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
:keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:paramtype disable_local_auth: bool
"""
super(ChannelSettings, self).__init__(**kwargs)
self.extension_key1 = extension_key1
self.extension_key2 = extension_key2
self.sites = sites
self.channel_id = channel_id
self.channel_display_name = channel_display_name
self.bot_id = bot_id
self.bot_icon_url = bot_icon_url
self.is_enabled = is_enabled
self.disable_local_auth = disable_local_auth
class CheckNameAvailabilityRequestBody(msrest.serialization.Model):
"""The request body for a request to Bot Service Management to check availability of a bot name.
:ivar name: the name of the bot for which availability needs to be checked.
:vartype name: str
:ivar type: the type of the bot for which availability needs to be checked.
:vartype type: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
*,
name: Optional[str] = None,
type: Optional[str] = None,
**kwargs
):
"""
:keyword name: the name of the bot for which availability needs to be checked.
:paramtype name: str
:keyword type: the type of the bot for which availability needs to be checked.
:paramtype type: str
"""
super(CheckNameAvailabilityRequestBody, self).__init__(**kwargs)
self.name = name
self.type = type
class CheckNameAvailabilityResponseBody(msrest.serialization.Model):
"""The response body returned for a request to Bot Service Management to check availability of a bot name.
:ivar valid: indicates if the bot name is valid.
:vartype valid: bool
:ivar message: additional message from the bot management api showing why a bot name is not
available.
:vartype message: str
"""
_attribute_map = {
'valid': {'key': 'valid', 'type': 'bool'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
*,
valid: Optional[bool] = None,
message: Optional[str] = None,
**kwargs
):
"""
:keyword valid: indicates if the bot name is valid.
:paramtype valid: bool
:keyword message: additional message from the bot management api showing why a bot name is not
available.
:paramtype message: str
"""
super(CheckNameAvailabilityResponseBody, self).__init__(**kwargs)
self.valid = valid
self.message = message
class ConnectionItemName(msrest.serialization.Model):
"""The display name of a connection Item Setting registered with the Bot.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Connection Item name that has been added in the API.
:vartype name: str
"""
_validation = {
'name': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(ConnectionItemName, self).__init__(**kwargs)
self.name = None
class ConnectionSetting(Resource):
"""Bot channel resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot channel resource.
:vartype properties: ~azure.mgmt.botservice.models.ConnectionSettingProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'ConnectionSettingProperties'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["ConnectionSettingProperties"] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.ConnectionSettingProperties
"""
super(ConnectionSetting, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, **kwargs)
self.properties = properties
class ConnectionSettingParameter(msrest.serialization.Model):
"""Extra Parameter in a Connection Setting Properties to indicate service provider specific properties.
:ivar key: Key for the Connection Setting Parameter.
:vartype key: str
:ivar value: Value associated with the Connection Setting Parameter.
:vartype value: str
"""
_attribute_map = {
'key': {'key': 'key', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
*,
key: Optional[str] = None,
value: Optional[str] = None,
**kwargs
):
"""
:keyword key: Key for the Connection Setting Parameter.
:paramtype key: str
:keyword value: Value associated with the Connection Setting Parameter.
:paramtype value: str
"""
super(ConnectionSettingParameter, self).__init__(**kwargs)
self.key = key
self.value = value
class ConnectionSettingProperties(msrest.serialization.Model):
"""Properties for a Connection Setting Item.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Id associated with the Connection Setting.
:vartype id: str
:ivar name: Name associated with the Connection Setting.
:vartype name: str
:ivar client_id: Client Id associated with the Connection Setting.
:vartype client_id: str
:ivar setting_id: Setting Id set by the service for the Connection Setting.
:vartype setting_id: str
:ivar client_secret: Client Secret associated with the Connection Setting.
:vartype client_secret: str
:ivar scopes: Scopes associated with the Connection Setting.
:vartype scopes: str
:ivar service_provider_id: Service Provider Id associated with the Connection Setting.
:vartype service_provider_id: str
:ivar service_provider_display_name: Service Provider Display Name associated with the
Connection Setting.
:vartype service_provider_display_name: str
:ivar parameters: Service Provider Parameters associated with the Connection Setting.
:vartype parameters: list[~azure.mgmt.botservice.models.ConnectionSettingParameter]
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'setting_id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'client_id': {'key': 'clientId', 'type': 'str'},
'setting_id': {'key': 'settingId', 'type': 'str'},
'client_secret': {'key': 'clientSecret', 'type': 'str'},
'scopes': {'key': 'scopes', 'type': 'str'},
'service_provider_id': {'key': 'serviceProviderId', 'type': 'str'},
'service_provider_display_name': {'key': 'serviceProviderDisplayName', 'type': 'str'},
'parameters': {'key': 'parameters', 'type': '[ConnectionSettingParameter]'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
}
def __init__(
self,
*,
id: Optional[str] = None,
name: Optional[str] = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
scopes: Optional[str] = None,
service_provider_id: Optional[str] = None,
service_provider_display_name: Optional[str] = None,
parameters: Optional[List["ConnectionSettingParameter"]] = None,
provisioning_state: Optional[str] = None,
**kwargs
):
"""
:keyword id: Id associated with the Connection Setting.
:paramtype id: str
:keyword name: Name associated with the Connection Setting.
:paramtype name: str
:keyword client_id: Client Id associated with the Connection Setting.
:paramtype client_id: str
:keyword client_secret: Client Secret associated with the Connection Setting.
:paramtype client_secret: str
:keyword scopes: Scopes associated with the Connection Setting.
:paramtype scopes: str
:keyword service_provider_id: Service Provider Id associated with the Connection Setting.
:paramtype service_provider_id: str
:keyword service_provider_display_name: Service Provider Display Name associated with the
Connection Setting.
:paramtype service_provider_display_name: str
:keyword parameters: Service Provider Parameters associated with the Connection Setting.
:paramtype parameters: list[~azure.mgmt.botservice.models.ConnectionSettingParameter]
:keyword provisioning_state: Provisioning state of the resource.
:paramtype provisioning_state: str
"""
super(ConnectionSettingProperties, self).__init__(**kwargs)
self.id = id
self.name = name
self.client_id = client_id
self.setting_id = None
self.client_secret = client_secret
self.scopes = scopes
self.service_provider_id = service_provider_id
self.service_provider_display_name = service_provider_display_name
self.parameters = parameters
self.provisioning_state = provisioning_state
class ConnectionSettingResponseList(msrest.serialization.Model):
"""The list of bot service connection settings response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service connection setting
resources.
:vartype next_link: str
:ivar value: Gets the list of bot service connection settings and their properties.
:vartype value: list[~azure.mgmt.botservice.models.ConnectionSetting]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[ConnectionSetting]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service connection setting
resources.
:paramtype next_link: str
"""
super(ConnectionSettingResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class DirectLineChannel(Channel):
"""Direct Line channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Direct Line channel resource.
:vartype properties: ~azure.mgmt.botservice.models.DirectLineChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'DirectLineChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["DirectLineChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Direct Line channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.DirectLineChannelProperties
"""
super(DirectLineChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'DirectLineChannel' # type: str
self.properties = properties
class DirectLineChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Direct Line channel.
:ivar sites: The list of Direct Line sites.
:vartype sites: list[~azure.mgmt.botservice.models.DirectLineSite]
:ivar direct_line_embed_code: Direct Line embed code of the resource.
:vartype direct_line_embed_code: str
"""
_attribute_map = {
'sites': {'key': 'sites', 'type': '[DirectLineSite]'},
'direct_line_embed_code': {'key': 'DirectLineEmbedCode', 'type': 'str'},
}
def __init__(
self,
*,
sites: Optional[List["DirectLineSite"]] = None,
direct_line_embed_code: Optional[str] = None,
**kwargs
):
"""
:keyword sites: The list of Direct Line sites.
:paramtype sites: list[~azure.mgmt.botservice.models.DirectLineSite]
:keyword direct_line_embed_code: Direct Line embed code of the resource.
:paramtype direct_line_embed_code: str
"""
super(DirectLineChannelProperties, self).__init__(**kwargs)
self.sites = sites
self.direct_line_embed_code = direct_line_embed_code
class DirectLineSite(msrest.serialization.Model):
"""A site for the Direct Line channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_v1_enabled: bool,
is_v3_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
"""
super(DirectLineSite, self).__init__(**kwargs)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
class DirectLineSpeechChannel(Channel):
"""DirectLine Speech channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to DirectLine Speech channel resource.
:vartype properties: ~azure.mgmt.botservice.models.DirectLineSpeechChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'DirectLineSpeechChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["DirectLineSpeechChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to DirectLine Speech channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.DirectLineSpeechChannelProperties
"""
super(DirectLineSpeechChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'DirectLineSpeechChannel' # type: str
self.properties = properties
class DirectLineSpeechChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the DirectLine Speech channel.
All required parameters must be populated in order to send to Azure.
:ivar cognitive_service_region: Required. The cognitive service region with this channel
registration.
:vartype cognitive_service_region: str
:ivar cognitive_service_subscription_key: Required. The cognitive service subscription key to
use with this channel registration.
:vartype cognitive_service_subscription_key: str
:ivar is_enabled: Whether this channel is enabled or not.
:vartype is_enabled: bool
:ivar custom_voice_deployment_id: Custom speech model id (optional).
:vartype custom_voice_deployment_id: str
:ivar custom_speech_model_id: Custom voice deployment id (optional).
:vartype custom_speech_model_id: str
:ivar is_default_bot_for_cog_svc_account: Make this a default bot for chosen cognitive service
account.
:vartype is_default_bot_for_cog_svc_account: bool
"""
_validation = {
'cognitive_service_region': {'required': True},
'cognitive_service_subscription_key': {'required': True},
}
_attribute_map = {
'cognitive_service_region': {'key': 'cognitiveServiceRegion', 'type': 'str'},
'cognitive_service_subscription_key': {'key': 'cognitiveServiceSubscriptionKey', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'custom_voice_deployment_id': {'key': 'customVoiceDeploymentId', 'type': 'str'},
'custom_speech_model_id': {'key': 'customSpeechModelId', 'type': 'str'},
'is_default_bot_for_cog_svc_account': {'key': 'isDefaultBotForCogSvcAccount', 'type': 'bool'},
}
def __init__(
self,
*,
cognitive_service_region: str,
cognitive_service_subscription_key: str,
is_enabled: Optional[bool] = None,
custom_voice_deployment_id: Optional[str] = None,
custom_speech_model_id: Optional[str] = None,
is_default_bot_for_cog_svc_account: Optional[bool] = None,
**kwargs
):
"""
:keyword cognitive_service_region: Required. The cognitive service region with this channel
registration.
:paramtype cognitive_service_region: str
:keyword cognitive_service_subscription_key: Required. The cognitive service subscription key
to use with this channel registration.
:paramtype cognitive_service_subscription_key: str
:keyword is_enabled: Whether this channel is enabled or not.
:paramtype is_enabled: bool
:keyword custom_voice_deployment_id: Custom speech model id (optional).
:paramtype custom_voice_deployment_id: str
:keyword custom_speech_model_id: Custom voice deployment id (optional).
:paramtype custom_speech_model_id: str
:keyword is_default_bot_for_cog_svc_account: Make this a default bot for chosen cognitive
service account.
:paramtype is_default_bot_for_cog_svc_account: bool
"""
super(DirectLineSpeechChannelProperties, self).__init__(**kwargs)
self.cognitive_service_region = cognitive_service_region
self.cognitive_service_subscription_key = cognitive_service_subscription_key
self.is_enabled = is_enabled
self.custom_voice_deployment_id = custom_voice_deployment_id
self.custom_speech_model_id = custom_speech_model_id
self.is_default_bot_for_cog_svc_account = is_default_bot_for_cog_svc_account
class EmailChannel(Channel):
"""Email channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to email channel resource.
:vartype properties: ~azure.mgmt.botservice.models.EmailChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'EmailChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["EmailChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to email channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.EmailChannelProperties
"""
super(EmailChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'EmailChannel' # type: str
self.properties = properties
class EmailChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Email channel.
All required parameters must be populated in order to send to Azure.
:ivar email_address: Required. The email address.
:vartype email_address: str
:ivar password: The password for the email address. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype password: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'email_address': {'required': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'email_address': {'key': 'emailAddress', 'type': 'str'},
'password': {'key': 'password', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
email_address: str,
is_enabled: bool,
password: Optional[str] = None,
**kwargs
):
"""
:keyword email_address: Required. The email address.
:paramtype email_address: str
:keyword password: The password for the email address. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype password: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(EmailChannelProperties, self).__init__(**kwargs)
self.email_address = email_address
self.password = password
self.is_enabled = is_enabled
class Error(msrest.serialization.Model):
"""Bot Service error object.
:ivar error: The error body.
:vartype error: ~azure.mgmt.botservice.models.ErrorBody
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'ErrorBody'},
}
def __init__(
self,
*,
error: Optional["ErrorBody"] = None,
**kwargs
):
"""
:keyword error: The error body.
:paramtype error: ~azure.mgmt.botservice.models.ErrorBody
"""
super(Error, self).__init__(**kwargs)
self.error = error
class ErrorBody(msrest.serialization.Model):
"""Bot Service error body.
All required parameters must be populated in order to send to Azure.
:ivar code: Required. error code.
:vartype code: str
:ivar message: Required. error message.
:vartype message: str
"""
_validation = {
'code': {'required': True},
'message': {'required': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
*,
code: str,
message: str,
**kwargs
):
"""
:keyword code: Required. error code.
:paramtype code: str
:keyword message: Required. error message.
:paramtype message: str
"""
super(ErrorBody, self).__init__(**kwargs)
self.code = code
self.message = message
class FacebookChannel(Channel):
"""Facebook channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to bot facebook channel.
:vartype properties: ~azure.mgmt.botservice.models.FacebookChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'FacebookChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["FacebookChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to bot facebook channel.
:paramtype properties: ~azure.mgmt.botservice.models.FacebookChannelProperties
"""
super(FacebookChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'FacebookChannel' # type: str
self.properties = properties
class FacebookChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Facebook channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar verify_token: Verify token. Value only returned through POST to the action Channel List
API, otherwise empty.
:vartype verify_token: str
:ivar pages: The list of Facebook pages.
:vartype pages: list[~azure.mgmt.botservice.models.FacebookPage]
:ivar app_id: Required. Facebook application id.
:vartype app_id: str
:ivar app_secret: Facebook application secret. Value only returned through POST to the action
Channel List API, otherwise empty.
:vartype app_secret: str
:ivar callback_url: Callback Url.
:vartype callback_url: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'verify_token': {'readonly': True},
'app_id': {'required': True},
'callback_url': {'readonly': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'verify_token': {'key': 'verifyToken', 'type': 'str'},
'pages': {'key': 'pages', 'type': '[FacebookPage]'},
'app_id': {'key': 'appId', 'type': 'str'},
'app_secret': {'key': 'appSecret', 'type': 'str'},
'callback_url': {'key': 'callbackUrl', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
app_id: str,
is_enabled: bool,
pages: Optional[List["FacebookPage"]] = None,
app_secret: Optional[str] = None,
**kwargs
):
"""
:keyword pages: The list of Facebook pages.
:paramtype pages: list[~azure.mgmt.botservice.models.FacebookPage]
:keyword app_id: Required. Facebook application id.
:paramtype app_id: str
:keyword app_secret: Facebook application secret. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype app_secret: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(FacebookChannelProperties, self).__init__(**kwargs)
self.verify_token = None
self.pages = pages
self.app_id = app_id
self.app_secret = app_secret
self.callback_url = None
self.is_enabled = is_enabled
class FacebookPage(msrest.serialization.Model):
"""A Facebook page for Facebook channel registration.
All required parameters must be populated in order to send to Azure.
:ivar id: Required. Page id.
:vartype id: str
:ivar access_token: Facebook application access token. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype access_token: str
"""
_validation = {
'id': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'access_token': {'key': 'accessToken', 'type': 'str'},
}
def __init__(
self,
*,
id: str,
access_token: Optional[str] = None,
**kwargs
):
"""
:keyword id: Required. Page id.
:paramtype id: str
:keyword access_token: Facebook application access token. Value only returned through POST to
the action Channel List API, otherwise empty.
:paramtype access_token: str
"""
super(FacebookPage, self).__init__(**kwargs)
self.id = id
self.access_token = access_token
class HostSettingsResponse(msrest.serialization.Model):
"""The response body returned for a request to Bot Service Management to check per subscription hostSettings.
:ivar o_auth_url: For in-conversation bot user authentication.
:vartype o_auth_url: str
:ivar to_bot_from_channel_open_id_metadata_url: For verifying incoming tokens from the
channels.
:vartype to_bot_from_channel_open_id_metadata_url: str
:ivar to_bot_from_channel_token_issuer: For verifying incoming tokens from the channels.
:vartype to_bot_from_channel_token_issuer: str
:ivar to_bot_from_emulator_open_id_metadata_url: For verifying incoming tokens from bot
emulator.
:vartype to_bot_from_emulator_open_id_metadata_url: str
:ivar to_channel_from_bot_login_url: For getting access token to channels from bot host.
:vartype to_channel_from_bot_login_url: str
:ivar to_channel_from_bot_o_auth_scope: For getting access token to channels from bot host.
:vartype to_channel_from_bot_o_auth_scope: str
:ivar validate_authority: Per cloud OAuth setting on whether authority is validated.
:vartype validate_authority: bool
:ivar bot_open_id_metadata: Same as toBotFromChannelOpenIdMetadataUrl, used by SDK < v4.12.
:vartype bot_open_id_metadata: str
"""
_attribute_map = {
'o_auth_url': {'key': 'OAuthUrl', 'type': 'str'},
'to_bot_from_channel_open_id_metadata_url': {'key': 'ToBotFromChannelOpenIdMetadataUrl', 'type': 'str'},
'to_bot_from_channel_token_issuer': {'key': 'ToBotFromChannelTokenIssuer', 'type': 'str'},
'to_bot_from_emulator_open_id_metadata_url': {'key': 'ToBotFromEmulatorOpenIdMetadataUrl', 'type': 'str'},
'to_channel_from_bot_login_url': {'key': 'ToChannelFromBotLoginUrl', 'type': 'str'},
'to_channel_from_bot_o_auth_scope': {'key': 'ToChannelFromBotOAuthScope', 'type': 'str'},
'validate_authority': {'key': 'ValidateAuthority', 'type': 'bool'},
'bot_open_id_metadata': {'key': 'BotOpenIdMetadata', 'type': 'str'},
}
def __init__(
self,
*,
o_auth_url: Optional[str] = None,
to_bot_from_channel_open_id_metadata_url: Optional[str] = None,
to_bot_from_channel_token_issuer: Optional[str] = None,
to_bot_from_emulator_open_id_metadata_url: Optional[str] = None,
to_channel_from_bot_login_url: Optional[str] = None,
to_channel_from_bot_o_auth_scope: Optional[str] = None,
validate_authority: Optional[bool] = None,
bot_open_id_metadata: Optional[str] = None,
**kwargs
):
"""
:keyword o_auth_url: For in-conversation bot user authentication.
:paramtype o_auth_url: str
:keyword to_bot_from_channel_open_id_metadata_url: For verifying incoming tokens from the
channels.
:paramtype to_bot_from_channel_open_id_metadata_url: str
:keyword to_bot_from_channel_token_issuer: For verifying incoming tokens from the channels.
:paramtype to_bot_from_channel_token_issuer: str
:keyword to_bot_from_emulator_open_id_metadata_url: For verifying incoming tokens from bot
emulator.
:paramtype to_bot_from_emulator_open_id_metadata_url: str
:keyword to_channel_from_bot_login_url: For getting access token to channels from bot host.
:paramtype to_channel_from_bot_login_url: str
:keyword to_channel_from_bot_o_auth_scope: For getting access token to channels from bot host.
:paramtype to_channel_from_bot_o_auth_scope: str
:keyword validate_authority: Per cloud OAuth setting on whether authority is validated.
:paramtype validate_authority: bool
:keyword bot_open_id_metadata: Same as toBotFromChannelOpenIdMetadataUrl, used by SDK < v4.12.
:paramtype bot_open_id_metadata: str
"""
super(HostSettingsResponse, self).__init__(**kwargs)
self.o_auth_url = o_auth_url
self.to_bot_from_channel_open_id_metadata_url = to_bot_from_channel_open_id_metadata_url
self.to_bot_from_channel_token_issuer = to_bot_from_channel_token_issuer
self.to_bot_from_emulator_open_id_metadata_url = to_bot_from_emulator_open_id_metadata_url
self.to_channel_from_bot_login_url = to_channel_from_bot_login_url
self.to_channel_from_bot_o_auth_scope = to_channel_from_bot_o_auth_scope
self.validate_authority = validate_authority
self.bot_open_id_metadata = bot_open_id_metadata
class KikChannel(Channel):
"""Kik channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Kik channel resource.
:vartype properties: ~azure.mgmt.botservice.models.KikChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'KikChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["KikChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Kik channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.KikChannelProperties
"""
super(KikChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'KikChannel' # type: str
self.properties = properties
class KikChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Kik channel.
All required parameters must be populated in order to send to Azure.
:ivar user_name: Required. The Kik user name.
:vartype user_name: str
:ivar api_key: Kik API key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype api_key: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'user_name': {'required': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'user_name': {'key': 'userName', 'type': 'str'},
'api_key': {'key': 'apiKey', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
user_name: str,
is_enabled: bool,
api_key: Optional[str] = None,
is_validated: Optional[bool] = None,
**kwargs
):
"""
:keyword user_name: Required. The Kik user name.
:paramtype user_name: str
:keyword api_key: Kik API key. Value only returned through POST to the action Channel List API,
otherwise empty.
:paramtype api_key: str
:keyword is_validated: Whether this channel is validated for the bot.
:paramtype is_validated: bool
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(KikChannelProperties, self).__init__(**kwargs)
self.user_name = user_name
self.api_key = api_key
self.is_validated = is_validated
self.is_enabled = is_enabled
class LineChannel(Channel):
"""Line channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to line channel resource.
:vartype properties: ~azure.mgmt.botservice.models.LineChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'LineChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["LineChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to line channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.LineChannelProperties
"""
super(LineChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'LineChannel' # type: str
self.properties = properties
class LineChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Line channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar line_registrations: Required. The list of line channel registrations.
:vartype line_registrations: list[~azure.mgmt.botservice.models.LineRegistration]
:ivar callback_url: Callback Url to enter in line registration.
:vartype callback_url: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
"""
_validation = {
'line_registrations': {'required': True},
'callback_url': {'readonly': True},
'is_validated': {'readonly': True},
}
_attribute_map = {
'line_registrations': {'key': 'lineRegistrations', 'type': '[LineRegistration]'},
'callback_url': {'key': 'callbackUrl', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
}
def __init__(
self,
*,
line_registrations: List["LineRegistration"],
**kwargs
):
"""
:keyword line_registrations: Required. The list of line channel registrations.
:paramtype line_registrations: list[~azure.mgmt.botservice.models.LineRegistration]
"""
super(LineChannelProperties, self).__init__(**kwargs)
self.line_registrations = line_registrations
self.callback_url = None
self.is_validated = None
class LineRegistration(msrest.serialization.Model):
"""The properties corresponding to a line channel registration.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar generated_id: Id generated for the line channel registration.
:vartype generated_id: str
:ivar channel_secret: Secret for the line channel registration.
:vartype channel_secret: str
:ivar channel_access_token: Access token for the line channel registration.
:vartype channel_access_token: str
"""
_validation = {
'generated_id': {'readonly': True},
}
_attribute_map = {
'generated_id': {'key': 'generatedId', 'type': 'str'},
'channel_secret': {'key': 'channelSecret', 'type': 'str'},
'channel_access_token': {'key': 'channelAccessToken', 'type': 'str'},
}
def __init__(
self,
*,
channel_secret: Optional[str] = None,
channel_access_token: Optional[str] = None,
**kwargs
):
"""
:keyword channel_secret: Secret for the line channel registration.
:paramtype channel_secret: str
:keyword channel_access_token: Access token for the line channel registration.
:paramtype channel_access_token: str
"""
super(LineRegistration, self).__init__(**kwargs)
self.generated_id = None
self.channel_secret = channel_secret
self.channel_access_token = channel_access_token
class ListChannelWithKeysResponse(BotChannel):
"""The ARM channel of list channel with keys operation response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot channel resource.
:vartype properties: ~azure.mgmt.botservice.models.Channel
:ivar resource: The set of properties specific to bot channel resource.
:vartype resource: ~azure.mgmt.botservice.models.Channel
:ivar setting: Channel settings.
:vartype setting: ~azure.mgmt.botservice.models.ChannelSettings
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar entity_tag: Entity tag of the resource.
:vartype entity_tag: str
:ivar changed_time: Changed time of the resource.
:vartype changed_time: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'Channel'},
'resource': {'key': 'resource', 'type': 'Channel'},
'setting': {'key': 'setting', 'type': 'ChannelSettings'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'entity_tag': {'key': 'entityTag', 'type': 'str'},
'changed_time': {'key': 'changedTime', 'type': 'str'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["Channel"] = None,
resource: Optional["Channel"] = None,
setting: Optional["ChannelSettings"] = None,
provisioning_state: Optional[str] = None,
entity_tag: Optional[str] = None,
changed_time: Optional[str] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.Channel
:keyword resource: The set of properties specific to bot channel resource.
:paramtype resource: ~azure.mgmt.botservice.models.Channel
:keyword setting: Channel settings.
:paramtype setting: ~azure.mgmt.botservice.models.ChannelSettings
:keyword provisioning_state: Provisioning state of the resource.
:paramtype provisioning_state: str
:keyword entity_tag: Entity tag of the resource.
:paramtype entity_tag: str
:keyword changed_time: Changed time of the resource.
:paramtype changed_time: str
"""
super(ListChannelWithKeysResponse, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties, **kwargs)
self.resource = resource
self.setting = setting
self.provisioning_state = provisioning_state
self.entity_tag = entity_tag
self.changed_time = changed_time
class MsTeamsChannel(Channel):
"""Microsoft Teams channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Microsoft Teams channel resource.
:vartype properties: ~azure.mgmt.botservice.models.MsTeamsChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'MsTeamsChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["MsTeamsChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Microsoft Teams channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.MsTeamsChannelProperties
"""
super(MsTeamsChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'MsTeamsChannel' # type: str
self.properties = properties
class MsTeamsChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Microsoft Teams channel.
All required parameters must be populated in order to send to Azure.
:ivar enable_calling: Enable calling for Microsoft Teams channel.
:vartype enable_calling: bool
:ivar calling_web_hook: Webhook for Microsoft Teams channel calls.
:vartype calling_web_hook: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
:ivar incoming_call_route: Webhook for Microsoft Teams channel calls.
:vartype incoming_call_route: str
:ivar deployment_environment: Deployment environment for Microsoft Teams channel calls.
:vartype deployment_environment: str
:ivar accepted_terms: Whether this channel accepted terms.
:vartype accepted_terms: bool
"""
_validation = {
'is_enabled': {'required': True},
}
_attribute_map = {
'enable_calling': {'key': 'enableCalling', 'type': 'bool'},
'calling_web_hook': {'key': 'callingWebHook', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'incoming_call_route': {'key': 'incomingCallRoute', 'type': 'str'},
'deployment_environment': {'key': 'deploymentEnvironment', 'type': 'str'},
'accepted_terms': {'key': 'acceptedTerms', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
enable_calling: Optional[bool] = None,
calling_web_hook: Optional[str] = None,
incoming_call_route: Optional[str] = None,
deployment_environment: Optional[str] = None,
accepted_terms: Optional[bool] = None,
**kwargs
):
"""
:keyword enable_calling: Enable calling for Microsoft Teams channel.
:paramtype enable_calling: bool
:keyword calling_web_hook: Webhook for Microsoft Teams channel calls.
:paramtype calling_web_hook: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
:keyword incoming_call_route: Webhook for Microsoft Teams channel calls.
:paramtype incoming_call_route: str
:keyword deployment_environment: Deployment environment for Microsoft Teams channel calls.
:paramtype deployment_environment: str
:keyword accepted_terms: Whether this channel accepted terms.
:paramtype accepted_terms: bool
"""
super(MsTeamsChannelProperties, self).__init__(**kwargs)
self.enable_calling = enable_calling
self.calling_web_hook = calling_web_hook
self.is_enabled = is_enabled
self.incoming_call_route = incoming_call_route
self.deployment_environment = deployment_environment
self.accepted_terms = accepted_terms
class OperationDisplayInfo(msrest.serialization.Model):
"""The operation supported by Bot Service Management.
:ivar description: The description of the operation.
:vartype description: str
:ivar operation: The action that users can perform, based on their permission level.
:vartype operation: str
:ivar provider: Service provider: Microsoft Bot Service.
:vartype provider: str
:ivar resource: Resource on which the operation is performed.
:vartype resource: str
"""
_attribute_map = {
'description': {'key': 'description', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
}
def __init__(
self,
*,
description: Optional[str] = None,
operation: Optional[str] = None,
provider: Optional[str] = None,
resource: Optional[str] = None,
**kwargs
):
"""
:keyword description: The description of the operation.
:paramtype description: str
:keyword operation: The action that users can perform, based on their permission level.
:paramtype operation: str
:keyword provider: Service provider: Microsoft Bot Service.
:paramtype provider: str
:keyword resource: Resource on which the operation is performed.
:paramtype resource: str
"""
super(OperationDisplayInfo, self).__init__(**kwargs)
self.description = description
self.operation = operation
self.provider = provider
self.resource = resource
class OperationEntity(msrest.serialization.Model):
"""The operations supported by Bot Service Management.
:ivar name: Operation name: {provider}/{resource}/{operation}.
:vartype name: str
:ivar display: The operation supported by Bot Service Management.
:vartype display: ~azure.mgmt.botservice.models.OperationDisplayInfo
:ivar origin: The origin of the operation.
:vartype origin: str
:ivar properties: Additional properties.
:vartype properties: any
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display': {'key': 'display', 'type': 'OperationDisplayInfo'},
'origin': {'key': 'origin', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'object'},
}
def __init__(
self,
*,
name: Optional[str] = None,
display: Optional["OperationDisplayInfo"] = None,
origin: Optional[str] = None,
properties: Optional[Any] = None,
**kwargs
):
"""
:keyword name: Operation name: {provider}/{resource}/{operation}.
:paramtype name: str
:keyword display: The operation supported by Bot Service Management.
:paramtype display: ~azure.mgmt.botservice.models.OperationDisplayInfo
:keyword origin: The origin of the operation.
:paramtype origin: str
:keyword properties: Additional properties.
:paramtype properties: any
"""
super(OperationEntity, self).__init__(**kwargs)
self.name = name
self.display = display
self.origin = origin
self.properties = properties
class OperationEntityListResult(msrest.serialization.Model):
"""The list of bot service operation response.
:ivar next_link: The link used to get the next page of operations.
:vartype next_link: str
:ivar value: The list of operations.
:vartype value: list[~azure.mgmt.botservice.models.OperationEntity]
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[OperationEntity]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
value: Optional[List["OperationEntity"]] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of operations.
:paramtype next_link: str
:keyword value: The list of operations.
:paramtype value: list[~azure.mgmt.botservice.models.OperationEntity]
"""
super(OperationEntityListResult, self).__init__(**kwargs)
self.next_link = next_link
self.value = value
class OperationResultsDescription(msrest.serialization.Model):
"""The properties indicating the operation result of an operation on a service.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The ID of the operation returned.
:vartype id: str
:ivar name: The name of the operation result.
:vartype name: str
:ivar status: The status of the operation being performed. Possible values include: "Canceled",
"Succeeded", "Failed", "Requested", "Running".
:vartype status: str or ~azure.mgmt.botservice.models.OperationResultStatus
:ivar start_time: The time that the operation was started.
:vartype start_time: ~datetime.datetime
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'status': {'readonly': True},
'start_time': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(OperationResultsDescription, self).__init__(**kwargs)
self.id = None
self.name = None
self.status = None
self.start_time = None
class PrivateEndpoint(msrest.serialization.Model):
"""The Private Endpoint resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The ARM identifier for Private Endpoint.
:vartype id: str
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(PrivateEndpoint, self).__init__(**kwargs)
self.id = None
class PrivateLinkResourceBase(msrest.serialization.Model):
"""Common fields that are returned in the response for all BotService Private Link Resources.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(PrivateLinkResourceBase, self).__init__(**kwargs)
self.id = None
self.name = None
self.type = None
class PrivateEndpointConnection(PrivateLinkResourceBase):
"""The Private Endpoint Connection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar private_endpoint: The resource of private end point.
:vartype private_endpoint: ~azure.mgmt.botservice.models.PrivateEndpoint
:ivar private_link_service_connection_state: A collection of information about the state of the
connection between service consumer and provider.
:vartype private_link_service_connection_state:
~azure.mgmt.botservice.models.PrivateLinkServiceConnectionState
:ivar provisioning_state: The provisioning state of the private endpoint connection resource.
Possible values include: "Succeeded", "Creating", "Deleting", "Failed".
:vartype provisioning_state: str or
~azure.mgmt.botservice.models.PrivateEndpointConnectionProvisioningState
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'},
'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
*,
private_endpoint: Optional["PrivateEndpoint"] = None,
private_link_service_connection_state: Optional["PrivateLinkServiceConnectionState"] = None,
**kwargs
):
"""
:keyword private_endpoint: The resource of private end point.
:paramtype private_endpoint: ~azure.mgmt.botservice.models.PrivateEndpoint
:keyword private_link_service_connection_state: A collection of information about the state of
the connection between service consumer and provider.
:paramtype private_link_service_connection_state:
~azure.mgmt.botservice.models.PrivateLinkServiceConnectionState
"""
super(PrivateEndpointConnection, self).__init__(**kwargs)
self.private_endpoint = private_endpoint
self.private_link_service_connection_state = private_link_service_connection_state
self.provisioning_state = None
class PrivateEndpointConnectionListResult(msrest.serialization.Model):
"""List of private endpoint connection associated with the specified storage account.
:ivar value: Array of private endpoint connections.
:vartype value: list[~azure.mgmt.botservice.models.PrivateEndpointConnection]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'},
}
def __init__(
self,
*,
value: Optional[List["PrivateEndpointConnection"]] = None,
**kwargs
):
"""
:keyword value: Array of private endpoint connections.
:paramtype value: list[~azure.mgmt.botservice.models.PrivateEndpointConnection]
"""
super(PrivateEndpointConnectionListResult, self).__init__(**kwargs)
self.value = value
class PrivateLinkResource(PrivateLinkResourceBase):
"""A private link resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar group_id: The private link resource group id.
:vartype group_id: str
:ivar required_members: The private link resource required member names.
:vartype required_members: list[str]
:ivar required_zone_names: The private link resource Private link DNS zone name.
:vartype required_zone_names: list[str]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'group_id': {'readonly': True},
'required_members': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'group_id': {'key': 'properties.groupId', 'type': 'str'},
'required_members': {'key': 'properties.requiredMembers', 'type': '[str]'},
'required_zone_names': {'key': 'properties.requiredZoneNames', 'type': '[str]'},
}
def __init__(
self,
*,
required_zone_names: Optional[List[str]] = None,
**kwargs
):
"""
:keyword required_zone_names: The private link resource Private link DNS zone name.
:paramtype required_zone_names: list[str]
"""
super(PrivateLinkResource, self).__init__(**kwargs)
self.group_id = None
self.required_members = None
self.required_zone_names = required_zone_names
class PrivateLinkResourceListResult(msrest.serialization.Model):
"""A list of private link resources.
:ivar value: Array of private link resources.
:vartype value: list[~azure.mgmt.botservice.models.PrivateLinkResource]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateLinkResource]'},
}
def __init__(
self,
*,
value: Optional[List["PrivateLinkResource"]] = None,
**kwargs
):
"""
:keyword value: Array of private link resources.
:paramtype value: list[~azure.mgmt.botservice.models.PrivateLinkResource]
"""
super(PrivateLinkResourceListResult, self).__init__(**kwargs)
self.value = value
class PrivateLinkServiceConnectionState(msrest.serialization.Model):
"""A collection of information about the state of the connection between service consumer and provider.
:ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner
of the service. Possible values include: "Pending", "Approved", "Rejected".
:vartype status: str or ~azure.mgmt.botservice.models.PrivateEndpointServiceConnectionStatus
:ivar description: The reason for approval/rejection of the connection.
:vartype description: str
:ivar actions_required: A message indicating if changes on the service provider require any
updates on the consumer.
:vartype actions_required: str
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'actions_required': {'key': 'actionsRequired', 'type': 'str'},
}
def __init__(
self,
*,
status: Optional[Union[str, "PrivateEndpointServiceConnectionStatus"]] = None,
description: Optional[str] = None,
actions_required: Optional[str] = None,
**kwargs
):
"""
:keyword status: Indicates whether the connection has been Approved/Rejected/Removed by the
owner of the service. Possible values include: "Pending", "Approved", "Rejected".
:paramtype status: str or ~azure.mgmt.botservice.models.PrivateEndpointServiceConnectionStatus
:keyword description: The reason for approval/rejection of the connection.
:paramtype description: str
:keyword actions_required: A message indicating if changes on the service provider require any
updates on the consumer.
:paramtype actions_required: str
"""
super(PrivateLinkServiceConnectionState, self).__init__(**kwargs)
self.status = status
self.description = description
self.actions_required = actions_required
class ServiceProvider(msrest.serialization.Model):
"""Service Provider Definition.
:ivar properties: The Properties of a Service Provider Object.
:vartype properties: ~azure.mgmt.botservice.models.ServiceProviderProperties
"""
_attribute_map = {
'properties': {'key': 'properties', 'type': 'ServiceProviderProperties'},
}
def __init__(
self,
*,
properties: Optional["ServiceProviderProperties"] = None,
**kwargs
):
"""
:keyword properties: The Properties of a Service Provider Object.
:paramtype properties: ~azure.mgmt.botservice.models.ServiceProviderProperties
"""
super(ServiceProvider, self).__init__(**kwargs)
self.properties = properties
class ServiceProviderParameter(msrest.serialization.Model):
"""Extra Parameters specific to each Service Provider.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Name of the Service Provider.
:vartype name: str
:ivar type: Type of the Service Provider.
:vartype type: str
:ivar display_name: Display Name of the Service Provider.
:vartype display_name: str
:ivar description: Description of the Service Provider.
:vartype description: str
:ivar help_url: Help Url for the Service Provider.
:vartype help_url: str
:ivar default: Default Name for the Service Provider.
:vartype default: str
:ivar metadata: Meta data for the Service Provider.
:vartype metadata: ~azure.mgmt.botservice.models.ServiceProviderParameterMetadata
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'display_name': {'readonly': True},
'description': {'readonly': True},
'help_url': {'readonly': True},
'default': {'readonly': True},
'metadata': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'help_url': {'key': 'helpUrl', 'type': 'str'},
'default': {'key': 'default', 'type': 'str'},
'metadata': {'key': 'metadata', 'type': 'ServiceProviderParameterMetadata'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(ServiceProviderParameter, self).__init__(**kwargs)
self.name = None
self.type = None
self.display_name = None
self.description = None
self.help_url = None
self.default = None
self.metadata = None
class ServiceProviderParameterMetadata(msrest.serialization.Model):
"""Meta data for the Service Provider.
:ivar constraints: the constraints of the bot meta data.
:vartype constraints: ~azure.mgmt.botservice.models.ServiceProviderParameterMetadataConstraints
"""
_attribute_map = {
'constraints': {'key': 'constraints', 'type': 'ServiceProviderParameterMetadataConstraints'},
}
def __init__(
self,
*,
constraints: Optional["ServiceProviderParameterMetadataConstraints"] = None,
**kwargs
):
"""
:keyword constraints: the constraints of the bot meta data.
:paramtype constraints:
~azure.mgmt.botservice.models.ServiceProviderParameterMetadataConstraints
"""
super(ServiceProviderParameterMetadata, self).__init__(**kwargs)
self.constraints = constraints
class ServiceProviderParameterMetadataConstraints(msrest.serialization.Model):
"""the constraints of the bot meta data.
:ivar required: Whether required the constraints of the bot meta data.
:vartype required: bool
"""
_attribute_map = {
'required': {'key': 'required', 'type': 'bool'},
}
def __init__(
self,
*,
required: Optional[bool] = None,
**kwargs
):
"""
:keyword required: Whether required the constraints of the bot meta data.
:paramtype required: bool
"""
super(ServiceProviderParameterMetadataConstraints, self).__init__(**kwargs)
self.required = required
class ServiceProviderProperties(msrest.serialization.Model):
"""The Object used to describe a Service Provider supported by Bot Service.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Id for Service Provider.
:vartype id: str
:ivar display_name: Display Name of the Service Provider.
:vartype display_name: str
:ivar service_provider_name: Display Name of the Service Provider.
:vartype service_provider_name: str
:ivar dev_portal_url: Display Name of the Service Provider.
:vartype dev_portal_url: str
:ivar icon_url: Display Name of the Service Provider.
:vartype icon_url: str
:ivar parameters: The list of parameters for the Service Provider.
:vartype parameters: list[~azure.mgmt.botservice.models.ServiceProviderParameter]
"""
_validation = {
'id': {'readonly': True},
'display_name': {'readonly': True},
'service_provider_name': {'readonly': True},
'dev_portal_url': {'readonly': True},
'icon_url': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'service_provider_name': {'key': 'serviceProviderName', 'type': 'str'},
'dev_portal_url': {'key': 'devPortalUrl', 'type': 'str'},
'icon_url': {'key': 'iconUrl', 'type': 'str'},
'parameters': {'key': 'parameters', 'type': '[ServiceProviderParameter]'},
}
def __init__(
self,
*,
parameters: Optional[List["ServiceProviderParameter"]] = None,
**kwargs
):
"""
:keyword parameters: The list of parameters for the Service Provider.
:paramtype parameters: list[~azure.mgmt.botservice.models.ServiceProviderParameter]
"""
super(ServiceProviderProperties, self).__init__(**kwargs)
self.id = None
self.display_name = None
self.service_provider_name = None
self.dev_portal_url = None
self.icon_url = None
self.parameters = parameters
class ServiceProviderResponseList(msrest.serialization.Model):
"""The list of bot service providers response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service providers.
:vartype next_link: str
:ivar value: Gets the list of bot service providers and their properties.
:vartype value: list[~azure.mgmt.botservice.models.ServiceProvider]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[ServiceProvider]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service providers.
:paramtype next_link: str
"""
super(ServiceProviderResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class WebChatSite(msrest.serialization.Model):
"""A site for the Webchat channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
"""
super(WebChatSite, self).__init__(**kwargs)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
class Site(WebChatSite, DirectLineSite):
"""A site for the channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
:ivar is_token_enabled: Whether this site is token enabled for channel.
:vartype is_token_enabled: bool
:ivar e_tag: Entity Tag.
:vartype e_tag: str
"""
_validation = {
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
'is_token_enabled': {'key': 'isTokenEnabled', 'type': 'bool'},
'e_tag': {'key': 'eTag', 'type': 'str'},
}
def __init__(
self,
*,
is_v1_enabled: bool,
is_v3_enabled: bool,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
is_token_enabled: Optional[bool] = None,
e_tag: Optional[str] = None,
**kwargs
):
"""
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
:keyword is_token_enabled: Whether this site is token enabled for channel.
:paramtype is_token_enabled: bool
:keyword e_tag: Entity Tag.
:paramtype e_tag: str
"""
super(Site, self).__init__(site_name=site_name, is_enabled=is_enabled, is_webchat_preview_enabled=is_webchat_preview_enabled, is_v1_enabled=is_v1_enabled, is_v3_enabled=is_v3_enabled, is_secure_site_enabled=is_secure_site_enabled, is_block_user_upload_enabled=is_block_user_upload_enabled, trusted_origins=trusted_origins, **kwargs)
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
class SiteInfo(msrest.serialization.Model):
"""Site information for WebChat or DirectLine Channels to identify which site to regenerate keys for.
All required parameters must be populated in order to send to Azure.
:ivar site_name: Required. The site name.
:vartype site_name: str
:ivar key: Required. Determines which key is to be regenerated. Possible values include:
"key1", "key2".
:vartype key: str or ~azure.mgmt.botservice.models.Key
"""
_validation = {
'site_name': {'required': True},
'key': {'required': True},
}
_attribute_map = {
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
}
def __init__(
self,
*,
site_name: str,
key: Union[str, "Key"],
**kwargs
):
"""
:keyword site_name: Required. The site name.
:paramtype site_name: str
:keyword key: Required. Determines which key is to be regenerated. Possible values include:
"key1", "key2".
:paramtype key: str or ~azure.mgmt.botservice.models.Key
"""
super(SiteInfo, self).__init__(**kwargs)
self.site_name = site_name
self.key = key
class Sku(msrest.serialization.Model):
"""The SKU of the cognitive services account.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar name: Required. The sku name. Possible values include: "F0", "S1".
:vartype name: str or ~azure.mgmt.botservice.models.SkuName
:ivar tier: Gets the sku tier. This is based on the SKU name. Possible values include: "Free",
"Standard".
:vartype tier: str or ~azure.mgmt.botservice.models.SkuTier
"""
_validation = {
'name': {'required': True},
'tier': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
}
def __init__(
self,
*,
name: Union[str, "SkuName"],
**kwargs
):
"""
:keyword name: Required. The sku name. Possible values include: "F0", "S1".
:paramtype name: str or ~azure.mgmt.botservice.models.SkuName
"""
super(Sku, self).__init__(**kwargs)
self.name = name
self.tier = None
class SkypeChannel(Channel):
"""Skype channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Skype channel resource.
:vartype properties: ~azure.mgmt.botservice.models.SkypeChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'SkypeChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["SkypeChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Skype channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.SkypeChannelProperties
"""
super(SkypeChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'SkypeChannel' # type: str
self.properties = properties
class SkypeChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Microsoft Teams channel.
All required parameters must be populated in order to send to Azure.
:ivar enable_messaging: Enable messaging for Skype channel.
:vartype enable_messaging: bool
:ivar enable_media_cards: Enable media cards for Skype channel.
:vartype enable_media_cards: bool
:ivar enable_video: Enable video for Skype channel.
:vartype enable_video: bool
:ivar enable_calling: Enable calling for Skype channel.
:vartype enable_calling: bool
:ivar enable_screen_sharing: Enable screen sharing for Skype channel.
:vartype enable_screen_sharing: bool
:ivar enable_groups: Enable groups for Skype channel.
:vartype enable_groups: bool
:ivar groups_mode: Group mode for Skype channel.
:vartype groups_mode: str
:ivar calling_web_hook: Calling web hook for Skype channel.
:vartype calling_web_hook: str
:ivar incoming_call_route: Incoming call route for Skype channel.
:vartype incoming_call_route: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'is_enabled': {'required': True},
}
_attribute_map = {
'enable_messaging': {'key': 'enableMessaging', 'type': 'bool'},
'enable_media_cards': {'key': 'enableMediaCards', 'type': 'bool'},
'enable_video': {'key': 'enableVideo', 'type': 'bool'},
'enable_calling': {'key': 'enableCalling', 'type': 'bool'},
'enable_screen_sharing': {'key': 'enableScreenSharing', 'type': 'bool'},
'enable_groups': {'key': 'enableGroups', 'type': 'bool'},
'groups_mode': {'key': 'groupsMode', 'type': 'str'},
'calling_web_hook': {'key': 'callingWebHook', 'type': 'str'},
'incoming_call_route': {'key': 'incomingCallRoute', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
enable_messaging: Optional[bool] = None,
enable_media_cards: Optional[bool] = None,
enable_video: Optional[bool] = None,
enable_calling: Optional[bool] = None,
enable_screen_sharing: Optional[bool] = None,
enable_groups: Optional[bool] = None,
groups_mode: Optional[str] = None,
calling_web_hook: Optional[str] = None,
incoming_call_route: Optional[str] = None,
**kwargs
):
"""
:keyword enable_messaging: Enable messaging for Skype channel.
:paramtype enable_messaging: bool
:keyword enable_media_cards: Enable media cards for Skype channel.
:paramtype enable_media_cards: bool
:keyword enable_video: Enable video for Skype channel.
:paramtype enable_video: bool
:keyword enable_calling: Enable calling for Skype channel.
:paramtype enable_calling: bool
:keyword enable_screen_sharing: Enable screen sharing for Skype channel.
:paramtype enable_screen_sharing: bool
:keyword enable_groups: Enable groups for Skype channel.
:paramtype enable_groups: bool
:keyword groups_mode: Group mode for Skype channel.
:paramtype groups_mode: str
:keyword calling_web_hook: Calling web hook for Skype channel.
:paramtype calling_web_hook: str
:keyword incoming_call_route: Incoming call route for Skype channel.
:paramtype incoming_call_route: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(SkypeChannelProperties, self).__init__(**kwargs)
self.enable_messaging = enable_messaging
self.enable_media_cards = enable_media_cards
self.enable_video = enable_video
self.enable_calling = enable_calling
self.enable_screen_sharing = enable_screen_sharing
self.enable_groups = enable_groups
self.groups_mode = groups_mode
self.calling_web_hook = calling_web_hook
self.incoming_call_route = incoming_call_route
self.is_enabled = is_enabled
class SlackChannel(Channel):
"""Slack channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Slack channel resource.
:vartype properties: ~azure.mgmt.botservice.models.SlackChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'SlackChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["SlackChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Slack channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.SlackChannelProperties
"""
super(SlackChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'SlackChannel' # type: str
self.properties = properties
class SlackChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Slack channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar client_id: The Slack client id.
:vartype client_id: str
:ivar client_secret: The Slack client secret. Value only returned through POST to the action
Channel List API, otherwise empty.
:vartype client_secret: str
:ivar verification_token: The Slack verification token. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype verification_token: str
:ivar scopes: The Slack permission scopes.
:vartype scopes: str
:ivar landing_page_url: The Slack landing page Url.
:vartype landing_page_url: str
:ivar redirect_action: The Slack redirect action.
:vartype redirect_action: str
:ivar last_submission_id: The Sms auth token.
:vartype last_submission_id: str
:ivar register_before_o_auth_flow: Whether to register the settings before OAuth validation is
performed. Recommended to True.
:vartype register_before_o_auth_flow: bool
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar signing_secret: The Slack signing secret.
:vartype signing_secret: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'redirect_action': {'readonly': True},
'last_submission_id': {'readonly': True},
'register_before_o_auth_flow': {'readonly': True},
'is_validated': {'readonly': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'client_id': {'key': 'clientId', 'type': 'str'},
'client_secret': {'key': 'clientSecret', 'type': 'str'},
'verification_token': {'key': 'verificationToken', 'type': 'str'},
'scopes': {'key': 'scopes', 'type': 'str'},
'landing_page_url': {'key': 'landingPageUrl', 'type': 'str'},
'redirect_action': {'key': 'redirectAction', 'type': 'str'},
'last_submission_id': {'key': 'lastSubmissionId', 'type': 'str'},
'register_before_o_auth_flow': {'key': 'registerBeforeOAuthFlow', 'type': 'bool'},
'is_validated': {'key': 'IsValidated', 'type': 'bool'},
'signing_secret': {'key': 'signingSecret', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
verification_token: Optional[str] = None,
scopes: Optional[str] = None,
landing_page_url: Optional[str] = None,
signing_secret: Optional[str] = None,
**kwargs
):
"""
:keyword client_id: The Slack client id.
:paramtype client_id: str
:keyword client_secret: The Slack client secret. Value only returned through POST to the action
Channel List API, otherwise empty.
:paramtype client_secret: str
:keyword verification_token: The Slack verification token. Value only returned through POST to
the action Channel List API, otherwise empty.
:paramtype verification_token: str
:keyword scopes: The Slack permission scopes.
:paramtype scopes: str
:keyword landing_page_url: The Slack landing page Url.
:paramtype landing_page_url: str
:keyword signing_secret: The Slack signing secret.
:paramtype signing_secret: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(SlackChannelProperties, self).__init__(**kwargs)
self.client_id = client_id
self.client_secret = client_secret
self.verification_token = verification_token
self.scopes = scopes
self.landing_page_url = landing_page_url
self.redirect_action = None
self.last_submission_id = None
self.register_before_o_auth_flow = None
self.is_validated = None
self.signing_secret = signing_secret
self.is_enabled = is_enabled
class SmsChannel(Channel):
"""Sms channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Sms channel resource.
:vartype properties: ~azure.mgmt.botservice.models.SmsChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'SmsChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["SmsChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Sms channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.SmsChannelProperties
"""
super(SmsChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'SmsChannel' # type: str
self.properties = properties
class SmsChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Sms channel.
All required parameters must be populated in order to send to Azure.
:ivar phone: Required. The Sms phone.
:vartype phone: str
:ivar account_sid: Required. The Sms account SID. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype account_sid: str
:ivar auth_token: The Sms auth token. Value only returned through POST to the action Channel
List API, otherwise empty.
:vartype auth_token: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'phone': {'required': True},
'account_sid': {'required': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'phone': {'key': 'phone', 'type': 'str'},
'account_sid': {'key': 'accountSID', 'type': 'str'},
'auth_token': {'key': 'authToken', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
phone: str,
account_sid: str,
is_enabled: bool,
auth_token: Optional[str] = None,
is_validated: Optional[bool] = None,
**kwargs
):
"""
:keyword phone: Required. The Sms phone.
:paramtype phone: str
:keyword account_sid: Required. The Sms account SID. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype account_sid: str
:keyword auth_token: The Sms auth token. Value only returned through POST to the action Channel
List API, otherwise empty.
:paramtype auth_token: str
:keyword is_validated: Whether this channel is validated for the bot.
:paramtype is_validated: bool
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(SmsChannelProperties, self).__init__(**kwargs)
self.phone = phone
self.account_sid = account_sid
self.auth_token = auth_token
self.is_validated = is_validated
self.is_enabled = is_enabled
class TelegramChannel(Channel):
"""Telegram channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Telegram channel resource.
:vartype properties: ~azure.mgmt.botservice.models.TelegramChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'TelegramChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["TelegramChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Telegram channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.TelegramChannelProperties
"""
super(TelegramChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'TelegramChannel' # type: str
self.properties = properties
class TelegramChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Telegram channel.
All required parameters must be populated in order to send to Azure.
:ivar access_token: The Telegram access token. Value only returned through POST to the action
Channel List API, otherwise empty.
:vartype access_token: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'is_enabled': {'required': True},
}
_attribute_map = {
'access_token': {'key': 'accessToken', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
access_token: Optional[str] = None,
is_validated: Optional[bool] = None,
**kwargs
):
"""
:keyword access_token: The Telegram access token. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype access_token: str
:keyword is_validated: Whether this channel is validated for the bot.
:paramtype is_validated: bool
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(TelegramChannelProperties, self).__init__(**kwargs)
self.access_token = access_token
self.is_validated = is_validated
self.is_enabled = is_enabled
class WebChatChannel(Channel):
"""Web Chat channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Web Chat channel resource.
:vartype properties: ~azure.mgmt.botservice.models.WebChatChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'WebChatChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["WebChatChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Web Chat channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.WebChatChannelProperties
"""
super(WebChatChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'WebChatChannel' # type: str
self.properties = properties
class WebChatChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Web Chat channel.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar web_chat_embed_code: Web chat control embed code.
:vartype web_chat_embed_code: str
:ivar sites: The list of Web Chat sites.
:vartype sites: list[~azure.mgmt.botservice.models.WebChatSite]
"""
_validation = {
'web_chat_embed_code': {'readonly': True},
}
_attribute_map = {
'web_chat_embed_code': {'key': 'webChatEmbedCode', 'type': 'str'},
'sites': {'key': 'sites', 'type': '[WebChatSite]'},
}
def __init__(
self,
*,
sites: Optional[List["WebChatSite"]] = None,
**kwargs
):
"""
:keyword sites: The list of Web Chat sites.
:paramtype sites: list[~azure.mgmt.botservice.models.WebChatSite]
"""
super(WebChatChannelProperties, self).__init__(**kwargs)
self.web_chat_embed_code = None
self.sites = sites
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/models/_models_py3.py
|
_models_py3.py
|
from typing import Any, Dict, List, Optional, Union
from azure.core.exceptions import HttpResponseError
import msrest.serialization
from ._azure_bot_service_enums import *
class Channel(msrest.serialization.Model):
"""Channel definition.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: AlexaChannel, DirectLineChannel, DirectLineSpeechChannel, EmailChannel, FacebookChannel, KikChannel, LineChannel, MsTeamsChannel, SkypeChannel, SlackChannel, SmsChannel, TelegramChannel, WebChatChannel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
}
_subtype_map = {
'channel_name': {'AlexaChannel': 'AlexaChannel', 'DirectLineChannel': 'DirectLineChannel', 'DirectLineSpeechChannel': 'DirectLineSpeechChannel', 'EmailChannel': 'EmailChannel', 'FacebookChannel': 'FacebookChannel', 'KikChannel': 'KikChannel', 'LineChannel': 'LineChannel', 'MsTeamsChannel': 'MsTeamsChannel', 'SkypeChannel': 'SkypeChannel', 'SlackChannel': 'SlackChannel', 'SmsChannel': 'SmsChannel', 'TelegramChannel': 'TelegramChannel', 'WebChatChannel': 'WebChatChannel'}
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
"""
super(Channel, self).__init__(**kwargs)
self.channel_name = None # type: Optional[str]
self.etag = etag
self.provisioning_state = None
self.location = location
class AlexaChannel(Channel):
"""Alexa channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Alexa channel resource.
:vartype properties: ~azure.mgmt.botservice.models.AlexaChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'AlexaChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["AlexaChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Alexa channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.AlexaChannelProperties
"""
super(AlexaChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'AlexaChannel' # type: str
self.properties = properties
class AlexaChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Alexa channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar alexa_skill_id: Required. The Alexa skill Id.
:vartype alexa_skill_id: str
:ivar url_fragment: Url fragment used in part of the Uri configured in Alexa.
:vartype url_fragment: str
:ivar service_endpoint_uri: Full Uri used to configured the skill in Alexa.
:vartype service_endpoint_uri: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'alexa_skill_id': {'required': True},
'url_fragment': {'readonly': True},
'service_endpoint_uri': {'readonly': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'alexa_skill_id': {'key': 'alexaSkillId', 'type': 'str'},
'url_fragment': {'key': 'urlFragment', 'type': 'str'},
'service_endpoint_uri': {'key': 'serviceEndpointUri', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
alexa_skill_id: str,
is_enabled: bool,
**kwargs
):
"""
:keyword alexa_skill_id: Required. The Alexa skill Id.
:paramtype alexa_skill_id: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(AlexaChannelProperties, self).__init__(**kwargs)
self.alexa_skill_id = alexa_skill_id
self.url_fragment = None
self.service_endpoint_uri = None
self.is_enabled = is_enabled
class Resource(msrest.serialization.Model):
"""Azure resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
"""
super(Resource, self).__init__(**kwargs)
self.id = None
self.name = None
self.location = location
self.type = None
self.tags = tags
self.sku = sku
self.kind = kind
self.etag = etag
self.zones = None
class Bot(Resource):
"""Bot resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot resource.
:vartype properties: ~azure.mgmt.botservice.models.BotProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'BotProperties'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["BotProperties"] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot resource.
:paramtype properties: ~azure.mgmt.botservice.models.BotProperties
"""
super(Bot, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, **kwargs)
self.properties = properties
class BotChannel(Resource):
"""Bot channel resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot channel resource.
:vartype properties: ~azure.mgmt.botservice.models.Channel
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'Channel'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["Channel"] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.Channel
"""
super(BotChannel, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, **kwargs)
self.properties = properties
class BotProperties(msrest.serialization.Model):
"""The parameters to provide for the Bot.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar display_name: Required. The Name of the bot.
:vartype display_name: str
:ivar description: The description of the bot.
:vartype description: str
:ivar icon_url: The Icon Url of the bot.
:vartype icon_url: str
:ivar endpoint: Required. The bot's endpoint.
:vartype endpoint: str
:ivar endpoint_version: The bot's endpoint version.
:vartype endpoint_version: str
:ivar all_settings: Contains resource all settings defined as key/value pairs.
:vartype all_settings: dict[str, str]
:ivar parameters: Contains resource parameters defined as key/value pairs.
:vartype parameters: dict[str, str]
:ivar manifest_url: The bot's manifest url.
:vartype manifest_url: str
:ivar msa_app_type: Microsoft App Type for the bot. Possible values include: "UserAssignedMSI",
"SingleTenant", "MultiTenant".
:vartype msa_app_type: str or ~azure.mgmt.botservice.models.MsaAppType
:ivar msa_app_id: Required. Microsoft App Id for the bot.
:vartype msa_app_id: str
:ivar msa_app_tenant_id: Microsoft App Tenant Id for the bot.
:vartype msa_app_tenant_id: str
:ivar msa_app_msi_resource_id: Microsoft App Managed Identity Resource Id for the bot.
:vartype msa_app_msi_resource_id: str
:ivar configured_channels: Collection of channels for which the bot is configured.
:vartype configured_channels: list[str]
:ivar enabled_channels: Collection of channels for which the bot is enabled.
:vartype enabled_channels: list[str]
:ivar developer_app_insight_key: The Application Insights key.
:vartype developer_app_insight_key: str
:ivar developer_app_insights_api_key: The Application Insights Api Key.
:vartype developer_app_insights_api_key: str
:ivar developer_app_insights_application_id: The Application Insights App Id.
:vartype developer_app_insights_application_id: str
:ivar luis_app_ids: Collection of LUIS App Ids.
:vartype luis_app_ids: list[str]
:ivar luis_key: The LUIS Key.
:vartype luis_key: str
:ivar is_cmek_enabled: Whether Cmek is enabled.
:vartype is_cmek_enabled: bool
:ivar cmek_key_vault_url: The CMK Url.
:vartype cmek_key_vault_url: str
:ivar cmek_encryption_status: The CMK encryption status.
:vartype cmek_encryption_status: str
:ivar public_network_access: Whether the bot is in an isolated network. Possible values
include: "Enabled", "Disabled". Default value: "Enabled".
:vartype public_network_access: str or ~azure.mgmt.botservice.models.PublicNetworkAccess
:ivar is_streaming_supported: Whether the bot is streaming supported.
:vartype is_streaming_supported: bool
:ivar is_developer_app_insights_api_key_set: Whether the bot is developerAppInsightsApiKey set.
:vartype is_developer_app_insights_api_key_set: bool
:ivar migration_token: Token used to migrate non Azure bot to azure subscription.
:vartype migration_token: str
:ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:vartype disable_local_auth: bool
:ivar schema_transformation_version: The channel schema transformation version for the bot.
:vartype schema_transformation_version: str
:ivar storage_resource_id: The storage resourceId for the bot.
:vartype storage_resource_id: str
:ivar private_endpoint_connections: List of Private Endpoint Connections configured for the
bot.
:vartype private_endpoint_connections:
list[~azure.mgmt.botservice.models.PrivateEndpointConnection]
:ivar open_with_hint: The hint to browser (e.g. protocol handler) on how to open the bot for
authoring.
:vartype open_with_hint: str
:ivar app_password_hint: The hint (e.g. keyVault secret resourceId) on how to fetch the app
secret.
:vartype app_password_hint: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar publishing_credentials: Publishing credentials of the resource.
:vartype publishing_credentials: str
"""
_validation = {
'display_name': {'required': True},
'endpoint': {'required': True},
'endpoint_version': {'readonly': True},
'msa_app_id': {'required': True},
'configured_channels': {'readonly': True},
'enabled_channels': {'readonly': True},
'cmek_encryption_status': {'readonly': True},
'is_developer_app_insights_api_key_set': {'readonly': True},
'migration_token': {'readonly': True},
'private_endpoint_connections': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'icon_url': {'key': 'iconUrl', 'type': 'str'},
'endpoint': {'key': 'endpoint', 'type': 'str'},
'endpoint_version': {'key': 'endpointVersion', 'type': 'str'},
'all_settings': {'key': 'allSettings', 'type': '{str}'},
'parameters': {'key': 'parameters', 'type': '{str}'},
'manifest_url': {'key': 'manifestUrl', 'type': 'str'},
'msa_app_type': {'key': 'msaAppType', 'type': 'str'},
'msa_app_id': {'key': 'msaAppId', 'type': 'str'},
'msa_app_tenant_id': {'key': 'msaAppTenantId', 'type': 'str'},
'msa_app_msi_resource_id': {'key': 'msaAppMSIResourceId', 'type': 'str'},
'configured_channels': {'key': 'configuredChannels', 'type': '[str]'},
'enabled_channels': {'key': 'enabledChannels', 'type': '[str]'},
'developer_app_insight_key': {'key': 'developerAppInsightKey', 'type': 'str'},
'developer_app_insights_api_key': {'key': 'developerAppInsightsApiKey', 'type': 'str'},
'developer_app_insights_application_id': {'key': 'developerAppInsightsApplicationId', 'type': 'str'},
'luis_app_ids': {'key': 'luisAppIds', 'type': '[str]'},
'luis_key': {'key': 'luisKey', 'type': 'str'},
'is_cmek_enabled': {'key': 'isCmekEnabled', 'type': 'bool'},
'cmek_key_vault_url': {'key': 'cmekKeyVaultUrl', 'type': 'str'},
'cmek_encryption_status': {'key': 'cmekEncryptionStatus', 'type': 'str'},
'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'},
'is_streaming_supported': {'key': 'isStreamingSupported', 'type': 'bool'},
'is_developer_app_insights_api_key_set': {'key': 'isDeveloperAppInsightsApiKeySet', 'type': 'bool'},
'migration_token': {'key': 'migrationToken', 'type': 'str'},
'disable_local_auth': {'key': 'disableLocalAuth', 'type': 'bool'},
'schema_transformation_version': {'key': 'schemaTransformationVersion', 'type': 'str'},
'storage_resource_id': {'key': 'storageResourceId', 'type': 'str'},
'private_endpoint_connections': {'key': 'privateEndpointConnections', 'type': '[PrivateEndpointConnection]'},
'open_with_hint': {'key': 'openWithHint', 'type': 'str'},
'app_password_hint': {'key': 'appPasswordHint', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'publishing_credentials': {'key': 'publishingCredentials', 'type': 'str'},
}
def __init__(
self,
*,
display_name: str,
endpoint: str,
msa_app_id: str,
description: Optional[str] = None,
icon_url: Optional[str] = None,
all_settings: Optional[Dict[str, str]] = None,
parameters: Optional[Dict[str, str]] = None,
manifest_url: Optional[str] = None,
msa_app_type: Optional[Union[str, "MsaAppType"]] = None,
msa_app_tenant_id: Optional[str] = None,
msa_app_msi_resource_id: Optional[str] = None,
developer_app_insight_key: Optional[str] = None,
developer_app_insights_api_key: Optional[str] = None,
developer_app_insights_application_id: Optional[str] = None,
luis_app_ids: Optional[List[str]] = None,
luis_key: Optional[str] = None,
is_cmek_enabled: Optional[bool] = None,
cmek_key_vault_url: Optional[str] = None,
public_network_access: Optional[Union[str, "PublicNetworkAccess"]] = "Enabled",
is_streaming_supported: Optional[bool] = False,
disable_local_auth: Optional[bool] = None,
schema_transformation_version: Optional[str] = None,
storage_resource_id: Optional[str] = None,
open_with_hint: Optional[str] = None,
app_password_hint: Optional[str] = None,
publishing_credentials: Optional[str] = None,
**kwargs
):
"""
:keyword display_name: Required. The Name of the bot.
:paramtype display_name: str
:keyword description: The description of the bot.
:paramtype description: str
:keyword icon_url: The Icon Url of the bot.
:paramtype icon_url: str
:keyword endpoint: Required. The bot's endpoint.
:paramtype endpoint: str
:keyword all_settings: Contains resource all settings defined as key/value pairs.
:paramtype all_settings: dict[str, str]
:keyword parameters: Contains resource parameters defined as key/value pairs.
:paramtype parameters: dict[str, str]
:keyword manifest_url: The bot's manifest url.
:paramtype manifest_url: str
:keyword msa_app_type: Microsoft App Type for the bot. Possible values include:
"UserAssignedMSI", "SingleTenant", "MultiTenant".
:paramtype msa_app_type: str or ~azure.mgmt.botservice.models.MsaAppType
:keyword msa_app_id: Required. Microsoft App Id for the bot.
:paramtype msa_app_id: str
:keyword msa_app_tenant_id: Microsoft App Tenant Id for the bot.
:paramtype msa_app_tenant_id: str
:keyword msa_app_msi_resource_id: Microsoft App Managed Identity Resource Id for the bot.
:paramtype msa_app_msi_resource_id: str
:keyword developer_app_insight_key: The Application Insights key.
:paramtype developer_app_insight_key: str
:keyword developer_app_insights_api_key: The Application Insights Api Key.
:paramtype developer_app_insights_api_key: str
:keyword developer_app_insights_application_id: The Application Insights App Id.
:paramtype developer_app_insights_application_id: str
:keyword luis_app_ids: Collection of LUIS App Ids.
:paramtype luis_app_ids: list[str]
:keyword luis_key: The LUIS Key.
:paramtype luis_key: str
:keyword is_cmek_enabled: Whether Cmek is enabled.
:paramtype is_cmek_enabled: bool
:keyword cmek_key_vault_url: The CMK Url.
:paramtype cmek_key_vault_url: str
:keyword public_network_access: Whether the bot is in an isolated network. Possible values
include: "Enabled", "Disabled". Default value: "Enabled".
:paramtype public_network_access: str or ~azure.mgmt.botservice.models.PublicNetworkAccess
:keyword is_streaming_supported: Whether the bot is streaming supported.
:paramtype is_streaming_supported: bool
:keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:paramtype disable_local_auth: bool
:keyword schema_transformation_version: The channel schema transformation version for the bot.
:paramtype schema_transformation_version: str
:keyword storage_resource_id: The storage resourceId for the bot.
:paramtype storage_resource_id: str
:keyword open_with_hint: The hint to browser (e.g. protocol handler) on how to open the bot for
authoring.
:paramtype open_with_hint: str
:keyword app_password_hint: The hint (e.g. keyVault secret resourceId) on how to fetch the app
secret.
:paramtype app_password_hint: str
:keyword publishing_credentials: Publishing credentials of the resource.
:paramtype publishing_credentials: str
"""
super(BotProperties, self).__init__(**kwargs)
self.display_name = display_name
self.description = description
self.icon_url = icon_url
self.endpoint = endpoint
self.endpoint_version = None
self.all_settings = all_settings
self.parameters = parameters
self.manifest_url = manifest_url
self.msa_app_type = msa_app_type
self.msa_app_id = msa_app_id
self.msa_app_tenant_id = msa_app_tenant_id
self.msa_app_msi_resource_id = msa_app_msi_resource_id
self.configured_channels = None
self.enabled_channels = None
self.developer_app_insight_key = developer_app_insight_key
self.developer_app_insights_api_key = developer_app_insights_api_key
self.developer_app_insights_application_id = developer_app_insights_application_id
self.luis_app_ids = luis_app_ids
self.luis_key = luis_key
self.is_cmek_enabled = is_cmek_enabled
self.cmek_key_vault_url = cmek_key_vault_url
self.cmek_encryption_status = None
self.public_network_access = public_network_access
self.is_streaming_supported = is_streaming_supported
self.is_developer_app_insights_api_key_set = None
self.migration_token = None
self.disable_local_auth = disable_local_auth
self.schema_transformation_version = schema_transformation_version
self.storage_resource_id = storage_resource_id
self.private_endpoint_connections = None
self.open_with_hint = open_with_hint
self.app_password_hint = app_password_hint
self.provisioning_state = None
self.publishing_credentials = publishing_credentials
class BotResponseList(msrest.serialization.Model):
"""The list of bot service operation response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service resources.
:vartype next_link: str
:ivar value: Gets the list of bot service results and their properties.
:vartype value: list[~azure.mgmt.botservice.models.Bot]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[Bot]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service resources.
:paramtype next_link: str
"""
super(BotResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class ChannelResponseList(msrest.serialization.Model):
"""The list of bot service channel operation response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service channel resources.
:vartype next_link: str
:ivar value: Gets the list of bot service channel results and their properties.
:vartype value: list[~azure.mgmt.botservice.models.BotChannel]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[BotChannel]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service channel resources.
:paramtype next_link: str
"""
super(ChannelResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class ChannelSettings(msrest.serialization.Model):
"""Channel settings definition.
:ivar extension_key1: The extensionKey1.
:vartype extension_key1: str
:ivar extension_key2: The extensionKey2.
:vartype extension_key2: str
:ivar sites: The list of sites.
:vartype sites: list[~azure.mgmt.botservice.models.Site]
:ivar channel_id: The channel id.
:vartype channel_id: str
:ivar channel_display_name: The channel display name.
:vartype channel_display_name: str
:ivar bot_id: The bot id.
:vartype bot_id: str
:ivar bot_icon_url: The bot icon url.
:vartype bot_icon_url: str
:ivar is_enabled: Whether this channel is enabled for the bot.
:vartype is_enabled: bool
:ivar disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:vartype disable_local_auth: bool
"""
_attribute_map = {
'extension_key1': {'key': 'extensionKey1', 'type': 'str'},
'extension_key2': {'key': 'extensionKey2', 'type': 'str'},
'sites': {'key': 'sites', 'type': '[Site]'},
'channel_id': {'key': 'channelId', 'type': 'str'},
'channel_display_name': {'key': 'channelDisplayName', 'type': 'str'},
'bot_id': {'key': 'botId', 'type': 'str'},
'bot_icon_url': {'key': 'botIconUrl', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'disable_local_auth': {'key': 'disableLocalAuth', 'type': 'bool'},
}
def __init__(
self,
*,
extension_key1: Optional[str] = None,
extension_key2: Optional[str] = None,
sites: Optional[List["Site"]] = None,
channel_id: Optional[str] = None,
channel_display_name: Optional[str] = None,
bot_id: Optional[str] = None,
bot_icon_url: Optional[str] = None,
is_enabled: Optional[bool] = None,
disable_local_auth: Optional[bool] = None,
**kwargs
):
"""
:keyword extension_key1: The extensionKey1.
:paramtype extension_key1: str
:keyword extension_key2: The extensionKey2.
:paramtype extension_key2: str
:keyword sites: The list of sites.
:paramtype sites: list[~azure.mgmt.botservice.models.Site]
:keyword channel_id: The channel id.
:paramtype channel_id: str
:keyword channel_display_name: The channel display name.
:paramtype channel_display_name: str
:keyword bot_id: The bot id.
:paramtype bot_id: str
:keyword bot_icon_url: The bot icon url.
:paramtype bot_icon_url: str
:keyword is_enabled: Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
:keyword disable_local_auth: Opt-out of local authentication and ensure only MSI and AAD can be
used exclusively for authentication.
:paramtype disable_local_auth: bool
"""
super(ChannelSettings, self).__init__(**kwargs)
self.extension_key1 = extension_key1
self.extension_key2 = extension_key2
self.sites = sites
self.channel_id = channel_id
self.channel_display_name = channel_display_name
self.bot_id = bot_id
self.bot_icon_url = bot_icon_url
self.is_enabled = is_enabled
self.disable_local_auth = disable_local_auth
class CheckNameAvailabilityRequestBody(msrest.serialization.Model):
"""The request body for a request to Bot Service Management to check availability of a bot name.
:ivar name: the name of the bot for which availability needs to be checked.
:vartype name: str
:ivar type: the type of the bot for which availability needs to be checked.
:vartype type: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
*,
name: Optional[str] = None,
type: Optional[str] = None,
**kwargs
):
"""
:keyword name: the name of the bot for which availability needs to be checked.
:paramtype name: str
:keyword type: the type of the bot for which availability needs to be checked.
:paramtype type: str
"""
super(CheckNameAvailabilityRequestBody, self).__init__(**kwargs)
self.name = name
self.type = type
class CheckNameAvailabilityResponseBody(msrest.serialization.Model):
"""The response body returned for a request to Bot Service Management to check availability of a bot name.
:ivar valid: indicates if the bot name is valid.
:vartype valid: bool
:ivar message: additional message from the bot management api showing why a bot name is not
available.
:vartype message: str
"""
_attribute_map = {
'valid': {'key': 'valid', 'type': 'bool'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
*,
valid: Optional[bool] = None,
message: Optional[str] = None,
**kwargs
):
"""
:keyword valid: indicates if the bot name is valid.
:paramtype valid: bool
:keyword message: additional message from the bot management api showing why a bot name is not
available.
:paramtype message: str
"""
super(CheckNameAvailabilityResponseBody, self).__init__(**kwargs)
self.valid = valid
self.message = message
class ConnectionItemName(msrest.serialization.Model):
"""The display name of a connection Item Setting registered with the Bot.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Connection Item name that has been added in the API.
:vartype name: str
"""
_validation = {
'name': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(ConnectionItemName, self).__init__(**kwargs)
self.name = None
class ConnectionSetting(Resource):
"""Bot channel resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot channel resource.
:vartype properties: ~azure.mgmt.botservice.models.ConnectionSettingProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'ConnectionSettingProperties'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["ConnectionSettingProperties"] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.ConnectionSettingProperties
"""
super(ConnectionSetting, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, **kwargs)
self.properties = properties
class ConnectionSettingParameter(msrest.serialization.Model):
"""Extra Parameter in a Connection Setting Properties to indicate service provider specific properties.
:ivar key: Key for the Connection Setting Parameter.
:vartype key: str
:ivar value: Value associated with the Connection Setting Parameter.
:vartype value: str
"""
_attribute_map = {
'key': {'key': 'key', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
*,
key: Optional[str] = None,
value: Optional[str] = None,
**kwargs
):
"""
:keyword key: Key for the Connection Setting Parameter.
:paramtype key: str
:keyword value: Value associated with the Connection Setting Parameter.
:paramtype value: str
"""
super(ConnectionSettingParameter, self).__init__(**kwargs)
self.key = key
self.value = value
class ConnectionSettingProperties(msrest.serialization.Model):
"""Properties for a Connection Setting Item.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Id associated with the Connection Setting.
:vartype id: str
:ivar name: Name associated with the Connection Setting.
:vartype name: str
:ivar client_id: Client Id associated with the Connection Setting.
:vartype client_id: str
:ivar setting_id: Setting Id set by the service for the Connection Setting.
:vartype setting_id: str
:ivar client_secret: Client Secret associated with the Connection Setting.
:vartype client_secret: str
:ivar scopes: Scopes associated with the Connection Setting.
:vartype scopes: str
:ivar service_provider_id: Service Provider Id associated with the Connection Setting.
:vartype service_provider_id: str
:ivar service_provider_display_name: Service Provider Display Name associated with the
Connection Setting.
:vartype service_provider_display_name: str
:ivar parameters: Service Provider Parameters associated with the Connection Setting.
:vartype parameters: list[~azure.mgmt.botservice.models.ConnectionSettingParameter]
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'setting_id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'client_id': {'key': 'clientId', 'type': 'str'},
'setting_id': {'key': 'settingId', 'type': 'str'},
'client_secret': {'key': 'clientSecret', 'type': 'str'},
'scopes': {'key': 'scopes', 'type': 'str'},
'service_provider_id': {'key': 'serviceProviderId', 'type': 'str'},
'service_provider_display_name': {'key': 'serviceProviderDisplayName', 'type': 'str'},
'parameters': {'key': 'parameters', 'type': '[ConnectionSettingParameter]'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
}
def __init__(
self,
*,
id: Optional[str] = None,
name: Optional[str] = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
scopes: Optional[str] = None,
service_provider_id: Optional[str] = None,
service_provider_display_name: Optional[str] = None,
parameters: Optional[List["ConnectionSettingParameter"]] = None,
provisioning_state: Optional[str] = None,
**kwargs
):
"""
:keyword id: Id associated with the Connection Setting.
:paramtype id: str
:keyword name: Name associated with the Connection Setting.
:paramtype name: str
:keyword client_id: Client Id associated with the Connection Setting.
:paramtype client_id: str
:keyword client_secret: Client Secret associated with the Connection Setting.
:paramtype client_secret: str
:keyword scopes: Scopes associated with the Connection Setting.
:paramtype scopes: str
:keyword service_provider_id: Service Provider Id associated with the Connection Setting.
:paramtype service_provider_id: str
:keyword service_provider_display_name: Service Provider Display Name associated with the
Connection Setting.
:paramtype service_provider_display_name: str
:keyword parameters: Service Provider Parameters associated with the Connection Setting.
:paramtype parameters: list[~azure.mgmt.botservice.models.ConnectionSettingParameter]
:keyword provisioning_state: Provisioning state of the resource.
:paramtype provisioning_state: str
"""
super(ConnectionSettingProperties, self).__init__(**kwargs)
self.id = id
self.name = name
self.client_id = client_id
self.setting_id = None
self.client_secret = client_secret
self.scopes = scopes
self.service_provider_id = service_provider_id
self.service_provider_display_name = service_provider_display_name
self.parameters = parameters
self.provisioning_state = provisioning_state
class ConnectionSettingResponseList(msrest.serialization.Model):
"""The list of bot service connection settings response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service connection setting
resources.
:vartype next_link: str
:ivar value: Gets the list of bot service connection settings and their properties.
:vartype value: list[~azure.mgmt.botservice.models.ConnectionSetting]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[ConnectionSetting]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service connection setting
resources.
:paramtype next_link: str
"""
super(ConnectionSettingResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class DirectLineChannel(Channel):
"""Direct Line channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Direct Line channel resource.
:vartype properties: ~azure.mgmt.botservice.models.DirectLineChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'DirectLineChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["DirectLineChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Direct Line channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.DirectLineChannelProperties
"""
super(DirectLineChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'DirectLineChannel' # type: str
self.properties = properties
class DirectLineChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Direct Line channel.
:ivar sites: The list of Direct Line sites.
:vartype sites: list[~azure.mgmt.botservice.models.DirectLineSite]
:ivar direct_line_embed_code: Direct Line embed code of the resource.
:vartype direct_line_embed_code: str
"""
_attribute_map = {
'sites': {'key': 'sites', 'type': '[DirectLineSite]'},
'direct_line_embed_code': {'key': 'DirectLineEmbedCode', 'type': 'str'},
}
def __init__(
self,
*,
sites: Optional[List["DirectLineSite"]] = None,
direct_line_embed_code: Optional[str] = None,
**kwargs
):
"""
:keyword sites: The list of Direct Line sites.
:paramtype sites: list[~azure.mgmt.botservice.models.DirectLineSite]
:keyword direct_line_embed_code: Direct Line embed code of the resource.
:paramtype direct_line_embed_code: str
"""
super(DirectLineChannelProperties, self).__init__(**kwargs)
self.sites = sites
self.direct_line_embed_code = direct_line_embed_code
class DirectLineSite(msrest.serialization.Model):
"""A site for the Direct Line channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_v1_enabled: bool,
is_v3_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
"""
super(DirectLineSite, self).__init__(**kwargs)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
class DirectLineSpeechChannel(Channel):
"""DirectLine Speech channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to DirectLine Speech channel resource.
:vartype properties: ~azure.mgmt.botservice.models.DirectLineSpeechChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'DirectLineSpeechChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["DirectLineSpeechChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to DirectLine Speech channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.DirectLineSpeechChannelProperties
"""
super(DirectLineSpeechChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'DirectLineSpeechChannel' # type: str
self.properties = properties
class DirectLineSpeechChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the DirectLine Speech channel.
All required parameters must be populated in order to send to Azure.
:ivar cognitive_service_region: Required. The cognitive service region with this channel
registration.
:vartype cognitive_service_region: str
:ivar cognitive_service_subscription_key: Required. The cognitive service subscription key to
use with this channel registration.
:vartype cognitive_service_subscription_key: str
:ivar is_enabled: Whether this channel is enabled or not.
:vartype is_enabled: bool
:ivar custom_voice_deployment_id: Custom speech model id (optional).
:vartype custom_voice_deployment_id: str
:ivar custom_speech_model_id: Custom voice deployment id (optional).
:vartype custom_speech_model_id: str
:ivar is_default_bot_for_cog_svc_account: Make this a default bot for chosen cognitive service
account.
:vartype is_default_bot_for_cog_svc_account: bool
"""
_validation = {
'cognitive_service_region': {'required': True},
'cognitive_service_subscription_key': {'required': True},
}
_attribute_map = {
'cognitive_service_region': {'key': 'cognitiveServiceRegion', 'type': 'str'},
'cognitive_service_subscription_key': {'key': 'cognitiveServiceSubscriptionKey', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'custom_voice_deployment_id': {'key': 'customVoiceDeploymentId', 'type': 'str'},
'custom_speech_model_id': {'key': 'customSpeechModelId', 'type': 'str'},
'is_default_bot_for_cog_svc_account': {'key': 'isDefaultBotForCogSvcAccount', 'type': 'bool'},
}
def __init__(
self,
*,
cognitive_service_region: str,
cognitive_service_subscription_key: str,
is_enabled: Optional[bool] = None,
custom_voice_deployment_id: Optional[str] = None,
custom_speech_model_id: Optional[str] = None,
is_default_bot_for_cog_svc_account: Optional[bool] = None,
**kwargs
):
"""
:keyword cognitive_service_region: Required. The cognitive service region with this channel
registration.
:paramtype cognitive_service_region: str
:keyword cognitive_service_subscription_key: Required. The cognitive service subscription key
to use with this channel registration.
:paramtype cognitive_service_subscription_key: str
:keyword is_enabled: Whether this channel is enabled or not.
:paramtype is_enabled: bool
:keyword custom_voice_deployment_id: Custom speech model id (optional).
:paramtype custom_voice_deployment_id: str
:keyword custom_speech_model_id: Custom voice deployment id (optional).
:paramtype custom_speech_model_id: str
:keyword is_default_bot_for_cog_svc_account: Make this a default bot for chosen cognitive
service account.
:paramtype is_default_bot_for_cog_svc_account: bool
"""
super(DirectLineSpeechChannelProperties, self).__init__(**kwargs)
self.cognitive_service_region = cognitive_service_region
self.cognitive_service_subscription_key = cognitive_service_subscription_key
self.is_enabled = is_enabled
self.custom_voice_deployment_id = custom_voice_deployment_id
self.custom_speech_model_id = custom_speech_model_id
self.is_default_bot_for_cog_svc_account = is_default_bot_for_cog_svc_account
class EmailChannel(Channel):
"""Email channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to email channel resource.
:vartype properties: ~azure.mgmt.botservice.models.EmailChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'EmailChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["EmailChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to email channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.EmailChannelProperties
"""
super(EmailChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'EmailChannel' # type: str
self.properties = properties
class EmailChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Email channel.
All required parameters must be populated in order to send to Azure.
:ivar email_address: Required. The email address.
:vartype email_address: str
:ivar password: The password for the email address. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype password: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'email_address': {'required': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'email_address': {'key': 'emailAddress', 'type': 'str'},
'password': {'key': 'password', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
email_address: str,
is_enabled: bool,
password: Optional[str] = None,
**kwargs
):
"""
:keyword email_address: Required. The email address.
:paramtype email_address: str
:keyword password: The password for the email address. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype password: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(EmailChannelProperties, self).__init__(**kwargs)
self.email_address = email_address
self.password = password
self.is_enabled = is_enabled
class Error(msrest.serialization.Model):
"""Bot Service error object.
:ivar error: The error body.
:vartype error: ~azure.mgmt.botservice.models.ErrorBody
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'ErrorBody'},
}
def __init__(
self,
*,
error: Optional["ErrorBody"] = None,
**kwargs
):
"""
:keyword error: The error body.
:paramtype error: ~azure.mgmt.botservice.models.ErrorBody
"""
super(Error, self).__init__(**kwargs)
self.error = error
class ErrorBody(msrest.serialization.Model):
"""Bot Service error body.
All required parameters must be populated in order to send to Azure.
:ivar code: Required. error code.
:vartype code: str
:ivar message: Required. error message.
:vartype message: str
"""
_validation = {
'code': {'required': True},
'message': {'required': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
*,
code: str,
message: str,
**kwargs
):
"""
:keyword code: Required. error code.
:paramtype code: str
:keyword message: Required. error message.
:paramtype message: str
"""
super(ErrorBody, self).__init__(**kwargs)
self.code = code
self.message = message
class FacebookChannel(Channel):
"""Facebook channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to bot facebook channel.
:vartype properties: ~azure.mgmt.botservice.models.FacebookChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'FacebookChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["FacebookChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to bot facebook channel.
:paramtype properties: ~azure.mgmt.botservice.models.FacebookChannelProperties
"""
super(FacebookChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'FacebookChannel' # type: str
self.properties = properties
class FacebookChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Facebook channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar verify_token: Verify token. Value only returned through POST to the action Channel List
API, otherwise empty.
:vartype verify_token: str
:ivar pages: The list of Facebook pages.
:vartype pages: list[~azure.mgmt.botservice.models.FacebookPage]
:ivar app_id: Required. Facebook application id.
:vartype app_id: str
:ivar app_secret: Facebook application secret. Value only returned through POST to the action
Channel List API, otherwise empty.
:vartype app_secret: str
:ivar callback_url: Callback Url.
:vartype callback_url: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'verify_token': {'readonly': True},
'app_id': {'required': True},
'callback_url': {'readonly': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'verify_token': {'key': 'verifyToken', 'type': 'str'},
'pages': {'key': 'pages', 'type': '[FacebookPage]'},
'app_id': {'key': 'appId', 'type': 'str'},
'app_secret': {'key': 'appSecret', 'type': 'str'},
'callback_url': {'key': 'callbackUrl', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
app_id: str,
is_enabled: bool,
pages: Optional[List["FacebookPage"]] = None,
app_secret: Optional[str] = None,
**kwargs
):
"""
:keyword pages: The list of Facebook pages.
:paramtype pages: list[~azure.mgmt.botservice.models.FacebookPage]
:keyword app_id: Required. Facebook application id.
:paramtype app_id: str
:keyword app_secret: Facebook application secret. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype app_secret: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(FacebookChannelProperties, self).__init__(**kwargs)
self.verify_token = None
self.pages = pages
self.app_id = app_id
self.app_secret = app_secret
self.callback_url = None
self.is_enabled = is_enabled
class FacebookPage(msrest.serialization.Model):
"""A Facebook page for Facebook channel registration.
All required parameters must be populated in order to send to Azure.
:ivar id: Required. Page id.
:vartype id: str
:ivar access_token: Facebook application access token. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype access_token: str
"""
_validation = {
'id': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'access_token': {'key': 'accessToken', 'type': 'str'},
}
def __init__(
self,
*,
id: str,
access_token: Optional[str] = None,
**kwargs
):
"""
:keyword id: Required. Page id.
:paramtype id: str
:keyword access_token: Facebook application access token. Value only returned through POST to
the action Channel List API, otherwise empty.
:paramtype access_token: str
"""
super(FacebookPage, self).__init__(**kwargs)
self.id = id
self.access_token = access_token
class HostSettingsResponse(msrest.serialization.Model):
"""The response body returned for a request to Bot Service Management to check per subscription hostSettings.
:ivar o_auth_url: For in-conversation bot user authentication.
:vartype o_auth_url: str
:ivar to_bot_from_channel_open_id_metadata_url: For verifying incoming tokens from the
channels.
:vartype to_bot_from_channel_open_id_metadata_url: str
:ivar to_bot_from_channel_token_issuer: For verifying incoming tokens from the channels.
:vartype to_bot_from_channel_token_issuer: str
:ivar to_bot_from_emulator_open_id_metadata_url: For verifying incoming tokens from bot
emulator.
:vartype to_bot_from_emulator_open_id_metadata_url: str
:ivar to_channel_from_bot_login_url: For getting access token to channels from bot host.
:vartype to_channel_from_bot_login_url: str
:ivar to_channel_from_bot_o_auth_scope: For getting access token to channels from bot host.
:vartype to_channel_from_bot_o_auth_scope: str
:ivar validate_authority: Per cloud OAuth setting on whether authority is validated.
:vartype validate_authority: bool
:ivar bot_open_id_metadata: Same as toBotFromChannelOpenIdMetadataUrl, used by SDK < v4.12.
:vartype bot_open_id_metadata: str
"""
_attribute_map = {
'o_auth_url': {'key': 'OAuthUrl', 'type': 'str'},
'to_bot_from_channel_open_id_metadata_url': {'key': 'ToBotFromChannelOpenIdMetadataUrl', 'type': 'str'},
'to_bot_from_channel_token_issuer': {'key': 'ToBotFromChannelTokenIssuer', 'type': 'str'},
'to_bot_from_emulator_open_id_metadata_url': {'key': 'ToBotFromEmulatorOpenIdMetadataUrl', 'type': 'str'},
'to_channel_from_bot_login_url': {'key': 'ToChannelFromBotLoginUrl', 'type': 'str'},
'to_channel_from_bot_o_auth_scope': {'key': 'ToChannelFromBotOAuthScope', 'type': 'str'},
'validate_authority': {'key': 'ValidateAuthority', 'type': 'bool'},
'bot_open_id_metadata': {'key': 'BotOpenIdMetadata', 'type': 'str'},
}
def __init__(
self,
*,
o_auth_url: Optional[str] = None,
to_bot_from_channel_open_id_metadata_url: Optional[str] = None,
to_bot_from_channel_token_issuer: Optional[str] = None,
to_bot_from_emulator_open_id_metadata_url: Optional[str] = None,
to_channel_from_bot_login_url: Optional[str] = None,
to_channel_from_bot_o_auth_scope: Optional[str] = None,
validate_authority: Optional[bool] = None,
bot_open_id_metadata: Optional[str] = None,
**kwargs
):
"""
:keyword o_auth_url: For in-conversation bot user authentication.
:paramtype o_auth_url: str
:keyword to_bot_from_channel_open_id_metadata_url: For verifying incoming tokens from the
channels.
:paramtype to_bot_from_channel_open_id_metadata_url: str
:keyword to_bot_from_channel_token_issuer: For verifying incoming tokens from the channels.
:paramtype to_bot_from_channel_token_issuer: str
:keyword to_bot_from_emulator_open_id_metadata_url: For verifying incoming tokens from bot
emulator.
:paramtype to_bot_from_emulator_open_id_metadata_url: str
:keyword to_channel_from_bot_login_url: For getting access token to channels from bot host.
:paramtype to_channel_from_bot_login_url: str
:keyword to_channel_from_bot_o_auth_scope: For getting access token to channels from bot host.
:paramtype to_channel_from_bot_o_auth_scope: str
:keyword validate_authority: Per cloud OAuth setting on whether authority is validated.
:paramtype validate_authority: bool
:keyword bot_open_id_metadata: Same as toBotFromChannelOpenIdMetadataUrl, used by SDK < v4.12.
:paramtype bot_open_id_metadata: str
"""
super(HostSettingsResponse, self).__init__(**kwargs)
self.o_auth_url = o_auth_url
self.to_bot_from_channel_open_id_metadata_url = to_bot_from_channel_open_id_metadata_url
self.to_bot_from_channel_token_issuer = to_bot_from_channel_token_issuer
self.to_bot_from_emulator_open_id_metadata_url = to_bot_from_emulator_open_id_metadata_url
self.to_channel_from_bot_login_url = to_channel_from_bot_login_url
self.to_channel_from_bot_o_auth_scope = to_channel_from_bot_o_auth_scope
self.validate_authority = validate_authority
self.bot_open_id_metadata = bot_open_id_metadata
class KikChannel(Channel):
"""Kik channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Kik channel resource.
:vartype properties: ~azure.mgmt.botservice.models.KikChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'KikChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["KikChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Kik channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.KikChannelProperties
"""
super(KikChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'KikChannel' # type: str
self.properties = properties
class KikChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Kik channel.
All required parameters must be populated in order to send to Azure.
:ivar user_name: Required. The Kik user name.
:vartype user_name: str
:ivar api_key: Kik API key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype api_key: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'user_name': {'required': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'user_name': {'key': 'userName', 'type': 'str'},
'api_key': {'key': 'apiKey', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
user_name: str,
is_enabled: bool,
api_key: Optional[str] = None,
is_validated: Optional[bool] = None,
**kwargs
):
"""
:keyword user_name: Required. The Kik user name.
:paramtype user_name: str
:keyword api_key: Kik API key. Value only returned through POST to the action Channel List API,
otherwise empty.
:paramtype api_key: str
:keyword is_validated: Whether this channel is validated for the bot.
:paramtype is_validated: bool
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(KikChannelProperties, self).__init__(**kwargs)
self.user_name = user_name
self.api_key = api_key
self.is_validated = is_validated
self.is_enabled = is_enabled
class LineChannel(Channel):
"""Line channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to line channel resource.
:vartype properties: ~azure.mgmt.botservice.models.LineChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'LineChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["LineChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to line channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.LineChannelProperties
"""
super(LineChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'LineChannel' # type: str
self.properties = properties
class LineChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Line channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar line_registrations: Required. The list of line channel registrations.
:vartype line_registrations: list[~azure.mgmt.botservice.models.LineRegistration]
:ivar callback_url: Callback Url to enter in line registration.
:vartype callback_url: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
"""
_validation = {
'line_registrations': {'required': True},
'callback_url': {'readonly': True},
'is_validated': {'readonly': True},
}
_attribute_map = {
'line_registrations': {'key': 'lineRegistrations', 'type': '[LineRegistration]'},
'callback_url': {'key': 'callbackUrl', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
}
def __init__(
self,
*,
line_registrations: List["LineRegistration"],
**kwargs
):
"""
:keyword line_registrations: Required. The list of line channel registrations.
:paramtype line_registrations: list[~azure.mgmt.botservice.models.LineRegistration]
"""
super(LineChannelProperties, self).__init__(**kwargs)
self.line_registrations = line_registrations
self.callback_url = None
self.is_validated = None
class LineRegistration(msrest.serialization.Model):
"""The properties corresponding to a line channel registration.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar generated_id: Id generated for the line channel registration.
:vartype generated_id: str
:ivar channel_secret: Secret for the line channel registration.
:vartype channel_secret: str
:ivar channel_access_token: Access token for the line channel registration.
:vartype channel_access_token: str
"""
_validation = {
'generated_id': {'readonly': True},
}
_attribute_map = {
'generated_id': {'key': 'generatedId', 'type': 'str'},
'channel_secret': {'key': 'channelSecret', 'type': 'str'},
'channel_access_token': {'key': 'channelAccessToken', 'type': 'str'},
}
def __init__(
self,
*,
channel_secret: Optional[str] = None,
channel_access_token: Optional[str] = None,
**kwargs
):
"""
:keyword channel_secret: Secret for the line channel registration.
:paramtype channel_secret: str
:keyword channel_access_token: Access token for the line channel registration.
:paramtype channel_access_token: str
"""
super(LineRegistration, self).__init__(**kwargs)
self.generated_id = None
self.channel_secret = channel_secret
self.channel_access_token = channel_access_token
class ListChannelWithKeysResponse(BotChannel):
"""The ARM channel of list channel with keys operation response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Specifies the resource ID.
:vartype id: str
:ivar name: Specifies the name of the resource.
:vartype name: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar type: Specifies the type of the resource.
:vartype type: str
:ivar tags: A set of tags. Contains resource tags defined as key/value pairs.
:vartype tags: dict[str, str]
:ivar sku: Gets or sets the SKU of the resource.
:vartype sku: ~azure.mgmt.botservice.models.Sku
:ivar kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:vartype kind: str or ~azure.mgmt.botservice.models.Kind
:ivar etag: Entity Tag.
:vartype etag: str
:ivar zones: Entity zones.
:vartype zones: list[str]
:ivar properties: The set of properties specific to bot channel resource.
:vartype properties: ~azure.mgmt.botservice.models.Channel
:ivar resource: The set of properties specific to bot channel resource.
:vartype resource: ~azure.mgmt.botservice.models.Channel
:ivar setting: Channel settings.
:vartype setting: ~azure.mgmt.botservice.models.ChannelSettings
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar entity_tag: Entity tag of the resource.
:vartype entity_tag: str
:ivar changed_time: Changed time of the resource.
:vartype changed_time: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'zones': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'Sku'},
'kind': {'key': 'kind', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'properties': {'key': 'properties', 'type': 'Channel'},
'resource': {'key': 'resource', 'type': 'Channel'},
'setting': {'key': 'setting', 'type': 'ChannelSettings'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'entity_tag': {'key': 'entityTag', 'type': 'str'},
'changed_time': {'key': 'changedTime', 'type': 'str'},
}
def __init__(
self,
*,
location: Optional[str] = None,
tags: Optional[Dict[str, str]] = None,
sku: Optional["Sku"] = None,
kind: Optional[Union[str, "Kind"]] = None,
etag: Optional[str] = None,
properties: Optional["Channel"] = None,
resource: Optional["Channel"] = None,
setting: Optional["ChannelSettings"] = None,
provisioning_state: Optional[str] = None,
entity_tag: Optional[str] = None,
changed_time: Optional[str] = None,
**kwargs
):
"""
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword tags: A set of tags. Contains resource tags defined as key/value pairs.
:paramtype tags: dict[str, str]
:keyword sku: Gets or sets the SKU of the resource.
:paramtype sku: ~azure.mgmt.botservice.models.Sku
:keyword kind: Required. Gets or sets the Kind of the resource. Possible values include: "sdk",
"designer", "bot", "function", "azurebot".
:paramtype kind: str or ~azure.mgmt.botservice.models.Kind
:keyword etag: Entity Tag.
:paramtype etag: str
:keyword properties: The set of properties specific to bot channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.Channel
:keyword resource: The set of properties specific to bot channel resource.
:paramtype resource: ~azure.mgmt.botservice.models.Channel
:keyword setting: Channel settings.
:paramtype setting: ~azure.mgmt.botservice.models.ChannelSettings
:keyword provisioning_state: Provisioning state of the resource.
:paramtype provisioning_state: str
:keyword entity_tag: Entity tag of the resource.
:paramtype entity_tag: str
:keyword changed_time: Changed time of the resource.
:paramtype changed_time: str
"""
super(ListChannelWithKeysResponse, self).__init__(location=location, tags=tags, sku=sku, kind=kind, etag=etag, properties=properties, **kwargs)
self.resource = resource
self.setting = setting
self.provisioning_state = provisioning_state
self.entity_tag = entity_tag
self.changed_time = changed_time
class MsTeamsChannel(Channel):
"""Microsoft Teams channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Microsoft Teams channel resource.
:vartype properties: ~azure.mgmt.botservice.models.MsTeamsChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'MsTeamsChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["MsTeamsChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Microsoft Teams channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.MsTeamsChannelProperties
"""
super(MsTeamsChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'MsTeamsChannel' # type: str
self.properties = properties
class MsTeamsChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Microsoft Teams channel.
All required parameters must be populated in order to send to Azure.
:ivar enable_calling: Enable calling for Microsoft Teams channel.
:vartype enable_calling: bool
:ivar calling_web_hook: Webhook for Microsoft Teams channel calls.
:vartype calling_web_hook: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
:ivar incoming_call_route: Webhook for Microsoft Teams channel calls.
:vartype incoming_call_route: str
:ivar deployment_environment: Deployment environment for Microsoft Teams channel calls.
:vartype deployment_environment: str
:ivar accepted_terms: Whether this channel accepted terms.
:vartype accepted_terms: bool
"""
_validation = {
'is_enabled': {'required': True},
}
_attribute_map = {
'enable_calling': {'key': 'enableCalling', 'type': 'bool'},
'calling_web_hook': {'key': 'callingWebHook', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'incoming_call_route': {'key': 'incomingCallRoute', 'type': 'str'},
'deployment_environment': {'key': 'deploymentEnvironment', 'type': 'str'},
'accepted_terms': {'key': 'acceptedTerms', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
enable_calling: Optional[bool] = None,
calling_web_hook: Optional[str] = None,
incoming_call_route: Optional[str] = None,
deployment_environment: Optional[str] = None,
accepted_terms: Optional[bool] = None,
**kwargs
):
"""
:keyword enable_calling: Enable calling for Microsoft Teams channel.
:paramtype enable_calling: bool
:keyword calling_web_hook: Webhook for Microsoft Teams channel calls.
:paramtype calling_web_hook: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
:keyword incoming_call_route: Webhook for Microsoft Teams channel calls.
:paramtype incoming_call_route: str
:keyword deployment_environment: Deployment environment for Microsoft Teams channel calls.
:paramtype deployment_environment: str
:keyword accepted_terms: Whether this channel accepted terms.
:paramtype accepted_terms: bool
"""
super(MsTeamsChannelProperties, self).__init__(**kwargs)
self.enable_calling = enable_calling
self.calling_web_hook = calling_web_hook
self.is_enabled = is_enabled
self.incoming_call_route = incoming_call_route
self.deployment_environment = deployment_environment
self.accepted_terms = accepted_terms
class OperationDisplayInfo(msrest.serialization.Model):
"""The operation supported by Bot Service Management.
:ivar description: The description of the operation.
:vartype description: str
:ivar operation: The action that users can perform, based on their permission level.
:vartype operation: str
:ivar provider: Service provider: Microsoft Bot Service.
:vartype provider: str
:ivar resource: Resource on which the operation is performed.
:vartype resource: str
"""
_attribute_map = {
'description': {'key': 'description', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
}
def __init__(
self,
*,
description: Optional[str] = None,
operation: Optional[str] = None,
provider: Optional[str] = None,
resource: Optional[str] = None,
**kwargs
):
"""
:keyword description: The description of the operation.
:paramtype description: str
:keyword operation: The action that users can perform, based on their permission level.
:paramtype operation: str
:keyword provider: Service provider: Microsoft Bot Service.
:paramtype provider: str
:keyword resource: Resource on which the operation is performed.
:paramtype resource: str
"""
super(OperationDisplayInfo, self).__init__(**kwargs)
self.description = description
self.operation = operation
self.provider = provider
self.resource = resource
class OperationEntity(msrest.serialization.Model):
"""The operations supported by Bot Service Management.
:ivar name: Operation name: {provider}/{resource}/{operation}.
:vartype name: str
:ivar display: The operation supported by Bot Service Management.
:vartype display: ~azure.mgmt.botservice.models.OperationDisplayInfo
:ivar origin: The origin of the operation.
:vartype origin: str
:ivar properties: Additional properties.
:vartype properties: any
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display': {'key': 'display', 'type': 'OperationDisplayInfo'},
'origin': {'key': 'origin', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'object'},
}
def __init__(
self,
*,
name: Optional[str] = None,
display: Optional["OperationDisplayInfo"] = None,
origin: Optional[str] = None,
properties: Optional[Any] = None,
**kwargs
):
"""
:keyword name: Operation name: {provider}/{resource}/{operation}.
:paramtype name: str
:keyword display: The operation supported by Bot Service Management.
:paramtype display: ~azure.mgmt.botservice.models.OperationDisplayInfo
:keyword origin: The origin of the operation.
:paramtype origin: str
:keyword properties: Additional properties.
:paramtype properties: any
"""
super(OperationEntity, self).__init__(**kwargs)
self.name = name
self.display = display
self.origin = origin
self.properties = properties
class OperationEntityListResult(msrest.serialization.Model):
"""The list of bot service operation response.
:ivar next_link: The link used to get the next page of operations.
:vartype next_link: str
:ivar value: The list of operations.
:vartype value: list[~azure.mgmt.botservice.models.OperationEntity]
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[OperationEntity]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
value: Optional[List["OperationEntity"]] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of operations.
:paramtype next_link: str
:keyword value: The list of operations.
:paramtype value: list[~azure.mgmt.botservice.models.OperationEntity]
"""
super(OperationEntityListResult, self).__init__(**kwargs)
self.next_link = next_link
self.value = value
class OperationResultsDescription(msrest.serialization.Model):
"""The properties indicating the operation result of an operation on a service.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The ID of the operation returned.
:vartype id: str
:ivar name: The name of the operation result.
:vartype name: str
:ivar status: The status of the operation being performed. Possible values include: "Canceled",
"Succeeded", "Failed", "Requested", "Running".
:vartype status: str or ~azure.mgmt.botservice.models.OperationResultStatus
:ivar start_time: The time that the operation was started.
:vartype start_time: ~datetime.datetime
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'status': {'readonly': True},
'start_time': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(OperationResultsDescription, self).__init__(**kwargs)
self.id = None
self.name = None
self.status = None
self.start_time = None
class PrivateEndpoint(msrest.serialization.Model):
"""The Private Endpoint resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The ARM identifier for Private Endpoint.
:vartype id: str
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(PrivateEndpoint, self).__init__(**kwargs)
self.id = None
class PrivateLinkResourceBase(msrest.serialization.Model):
"""Common fields that are returned in the response for all BotService Private Link Resources.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(PrivateLinkResourceBase, self).__init__(**kwargs)
self.id = None
self.name = None
self.type = None
class PrivateEndpointConnection(PrivateLinkResourceBase):
"""The Private Endpoint Connection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar private_endpoint: The resource of private end point.
:vartype private_endpoint: ~azure.mgmt.botservice.models.PrivateEndpoint
:ivar private_link_service_connection_state: A collection of information about the state of the
connection between service consumer and provider.
:vartype private_link_service_connection_state:
~azure.mgmt.botservice.models.PrivateLinkServiceConnectionState
:ivar provisioning_state: The provisioning state of the private endpoint connection resource.
Possible values include: "Succeeded", "Creating", "Deleting", "Failed".
:vartype provisioning_state: str or
~azure.mgmt.botservice.models.PrivateEndpointConnectionProvisioningState
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'},
'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
*,
private_endpoint: Optional["PrivateEndpoint"] = None,
private_link_service_connection_state: Optional["PrivateLinkServiceConnectionState"] = None,
**kwargs
):
"""
:keyword private_endpoint: The resource of private end point.
:paramtype private_endpoint: ~azure.mgmt.botservice.models.PrivateEndpoint
:keyword private_link_service_connection_state: A collection of information about the state of
the connection between service consumer and provider.
:paramtype private_link_service_connection_state:
~azure.mgmt.botservice.models.PrivateLinkServiceConnectionState
"""
super(PrivateEndpointConnection, self).__init__(**kwargs)
self.private_endpoint = private_endpoint
self.private_link_service_connection_state = private_link_service_connection_state
self.provisioning_state = None
class PrivateEndpointConnectionListResult(msrest.serialization.Model):
"""List of private endpoint connection associated with the specified storage account.
:ivar value: Array of private endpoint connections.
:vartype value: list[~azure.mgmt.botservice.models.PrivateEndpointConnection]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'},
}
def __init__(
self,
*,
value: Optional[List["PrivateEndpointConnection"]] = None,
**kwargs
):
"""
:keyword value: Array of private endpoint connections.
:paramtype value: list[~azure.mgmt.botservice.models.PrivateEndpointConnection]
"""
super(PrivateEndpointConnectionListResult, self).__init__(**kwargs)
self.value = value
class PrivateLinkResource(PrivateLinkResourceBase):
"""A private link resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:ivar group_id: The private link resource group id.
:vartype group_id: str
:ivar required_members: The private link resource required member names.
:vartype required_members: list[str]
:ivar required_zone_names: The private link resource Private link DNS zone name.
:vartype required_zone_names: list[str]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'group_id': {'readonly': True},
'required_members': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'group_id': {'key': 'properties.groupId', 'type': 'str'},
'required_members': {'key': 'properties.requiredMembers', 'type': '[str]'},
'required_zone_names': {'key': 'properties.requiredZoneNames', 'type': '[str]'},
}
def __init__(
self,
*,
required_zone_names: Optional[List[str]] = None,
**kwargs
):
"""
:keyword required_zone_names: The private link resource Private link DNS zone name.
:paramtype required_zone_names: list[str]
"""
super(PrivateLinkResource, self).__init__(**kwargs)
self.group_id = None
self.required_members = None
self.required_zone_names = required_zone_names
class PrivateLinkResourceListResult(msrest.serialization.Model):
"""A list of private link resources.
:ivar value: Array of private link resources.
:vartype value: list[~azure.mgmt.botservice.models.PrivateLinkResource]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateLinkResource]'},
}
def __init__(
self,
*,
value: Optional[List["PrivateLinkResource"]] = None,
**kwargs
):
"""
:keyword value: Array of private link resources.
:paramtype value: list[~azure.mgmt.botservice.models.PrivateLinkResource]
"""
super(PrivateLinkResourceListResult, self).__init__(**kwargs)
self.value = value
class PrivateLinkServiceConnectionState(msrest.serialization.Model):
"""A collection of information about the state of the connection between service consumer and provider.
:ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner
of the service. Possible values include: "Pending", "Approved", "Rejected".
:vartype status: str or ~azure.mgmt.botservice.models.PrivateEndpointServiceConnectionStatus
:ivar description: The reason for approval/rejection of the connection.
:vartype description: str
:ivar actions_required: A message indicating if changes on the service provider require any
updates on the consumer.
:vartype actions_required: str
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'actions_required': {'key': 'actionsRequired', 'type': 'str'},
}
def __init__(
self,
*,
status: Optional[Union[str, "PrivateEndpointServiceConnectionStatus"]] = None,
description: Optional[str] = None,
actions_required: Optional[str] = None,
**kwargs
):
"""
:keyword status: Indicates whether the connection has been Approved/Rejected/Removed by the
owner of the service. Possible values include: "Pending", "Approved", "Rejected".
:paramtype status: str or ~azure.mgmt.botservice.models.PrivateEndpointServiceConnectionStatus
:keyword description: The reason for approval/rejection of the connection.
:paramtype description: str
:keyword actions_required: A message indicating if changes on the service provider require any
updates on the consumer.
:paramtype actions_required: str
"""
super(PrivateLinkServiceConnectionState, self).__init__(**kwargs)
self.status = status
self.description = description
self.actions_required = actions_required
class ServiceProvider(msrest.serialization.Model):
"""Service Provider Definition.
:ivar properties: The Properties of a Service Provider Object.
:vartype properties: ~azure.mgmt.botservice.models.ServiceProviderProperties
"""
_attribute_map = {
'properties': {'key': 'properties', 'type': 'ServiceProviderProperties'},
}
def __init__(
self,
*,
properties: Optional["ServiceProviderProperties"] = None,
**kwargs
):
"""
:keyword properties: The Properties of a Service Provider Object.
:paramtype properties: ~azure.mgmt.botservice.models.ServiceProviderProperties
"""
super(ServiceProvider, self).__init__(**kwargs)
self.properties = properties
class ServiceProviderParameter(msrest.serialization.Model):
"""Extra Parameters specific to each Service Provider.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Name of the Service Provider.
:vartype name: str
:ivar type: Type of the Service Provider.
:vartype type: str
:ivar display_name: Display Name of the Service Provider.
:vartype display_name: str
:ivar description: Description of the Service Provider.
:vartype description: str
:ivar help_url: Help Url for the Service Provider.
:vartype help_url: str
:ivar default: Default Name for the Service Provider.
:vartype default: str
:ivar metadata: Meta data for the Service Provider.
:vartype metadata: ~azure.mgmt.botservice.models.ServiceProviderParameterMetadata
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'display_name': {'readonly': True},
'description': {'readonly': True},
'help_url': {'readonly': True},
'default': {'readonly': True},
'metadata': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'help_url': {'key': 'helpUrl', 'type': 'str'},
'default': {'key': 'default', 'type': 'str'},
'metadata': {'key': 'metadata', 'type': 'ServiceProviderParameterMetadata'},
}
def __init__(
self,
**kwargs
):
"""
"""
super(ServiceProviderParameter, self).__init__(**kwargs)
self.name = None
self.type = None
self.display_name = None
self.description = None
self.help_url = None
self.default = None
self.metadata = None
class ServiceProviderParameterMetadata(msrest.serialization.Model):
"""Meta data for the Service Provider.
:ivar constraints: the constraints of the bot meta data.
:vartype constraints: ~azure.mgmt.botservice.models.ServiceProviderParameterMetadataConstraints
"""
_attribute_map = {
'constraints': {'key': 'constraints', 'type': 'ServiceProviderParameterMetadataConstraints'},
}
def __init__(
self,
*,
constraints: Optional["ServiceProviderParameterMetadataConstraints"] = None,
**kwargs
):
"""
:keyword constraints: the constraints of the bot meta data.
:paramtype constraints:
~azure.mgmt.botservice.models.ServiceProviderParameterMetadataConstraints
"""
super(ServiceProviderParameterMetadata, self).__init__(**kwargs)
self.constraints = constraints
class ServiceProviderParameterMetadataConstraints(msrest.serialization.Model):
"""the constraints of the bot meta data.
:ivar required: Whether required the constraints of the bot meta data.
:vartype required: bool
"""
_attribute_map = {
'required': {'key': 'required', 'type': 'bool'},
}
def __init__(
self,
*,
required: Optional[bool] = None,
**kwargs
):
"""
:keyword required: Whether required the constraints of the bot meta data.
:paramtype required: bool
"""
super(ServiceProviderParameterMetadataConstraints, self).__init__(**kwargs)
self.required = required
class ServiceProviderProperties(msrest.serialization.Model):
"""The Object used to describe a Service Provider supported by Bot Service.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Id for Service Provider.
:vartype id: str
:ivar display_name: Display Name of the Service Provider.
:vartype display_name: str
:ivar service_provider_name: Display Name of the Service Provider.
:vartype service_provider_name: str
:ivar dev_portal_url: Display Name of the Service Provider.
:vartype dev_portal_url: str
:ivar icon_url: Display Name of the Service Provider.
:vartype icon_url: str
:ivar parameters: The list of parameters for the Service Provider.
:vartype parameters: list[~azure.mgmt.botservice.models.ServiceProviderParameter]
"""
_validation = {
'id': {'readonly': True},
'display_name': {'readonly': True},
'service_provider_name': {'readonly': True},
'dev_portal_url': {'readonly': True},
'icon_url': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'service_provider_name': {'key': 'serviceProviderName', 'type': 'str'},
'dev_portal_url': {'key': 'devPortalUrl', 'type': 'str'},
'icon_url': {'key': 'iconUrl', 'type': 'str'},
'parameters': {'key': 'parameters', 'type': '[ServiceProviderParameter]'},
}
def __init__(
self,
*,
parameters: Optional[List["ServiceProviderParameter"]] = None,
**kwargs
):
"""
:keyword parameters: The list of parameters for the Service Provider.
:paramtype parameters: list[~azure.mgmt.botservice.models.ServiceProviderParameter]
"""
super(ServiceProviderProperties, self).__init__(**kwargs)
self.id = None
self.display_name = None
self.service_provider_name = None
self.dev_portal_url = None
self.icon_url = None
self.parameters = parameters
class ServiceProviderResponseList(msrest.serialization.Model):
"""The list of bot service providers response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar next_link: The link used to get the next page of bot service providers.
:vartype next_link: str
:ivar value: Gets the list of bot service providers and their properties.
:vartype value: list[~azure.mgmt.botservice.models.ServiceProvider]
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'value': {'key': 'value', 'type': '[ServiceProvider]'},
}
def __init__(
self,
*,
next_link: Optional[str] = None,
**kwargs
):
"""
:keyword next_link: The link used to get the next page of bot service providers.
:paramtype next_link: str
"""
super(ServiceProviderResponseList, self).__init__(**kwargs)
self.next_link = next_link
self.value = None
class WebChatSite(msrest.serialization.Model):
"""A site for the Webchat channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
"""
_validation = {
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
**kwargs
):
"""
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
"""
super(WebChatSite, self).__init__(**kwargs)
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
class Site(WebChatSite, DirectLineSite):
"""A site for the channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v1_enabled: bool
:ivar is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:vartype is_v3_enabled: bool
:ivar is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:vartype is_secure_site_enabled: bool
:ivar is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:vartype is_block_user_upload_enabled: bool
:ivar trusted_origins: List of Trusted Origin URLs for this site. This field is applicable only
if isSecureSiteEnabled is True.
:vartype trusted_origins: list[str]
:ivar site_id: Site Id.
:vartype site_id: str
:ivar site_name: Required. Site name.
:vartype site_name: str
:ivar key: Primary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key: str
:ivar key2: Secondary key. Value only returned through POST to the action Channel List API,
otherwise empty.
:vartype key2: str
:ivar is_enabled: Required. Whether this site is enabled for DirectLine channel.
:vartype is_enabled: bool
:ivar is_webchat_preview_enabled: Required. Whether this site is enabled for preview versions
of Webchat.
:vartype is_webchat_preview_enabled: bool
:ivar is_token_enabled: Whether this site is token enabled for channel.
:vartype is_token_enabled: bool
:ivar e_tag: Entity Tag.
:vartype e_tag: str
"""
_validation = {
'is_v1_enabled': {'required': True},
'is_v3_enabled': {'required': True},
'site_id': {'readonly': True},
'site_name': {'required': True},
'key': {'readonly': True},
'key2': {'readonly': True},
'is_enabled': {'required': True},
'is_webchat_preview_enabled': {'required': True},
}
_attribute_map = {
'is_v1_enabled': {'key': 'isV1Enabled', 'type': 'bool'},
'is_v3_enabled': {'key': 'isV3Enabled', 'type': 'bool'},
'is_secure_site_enabled': {'key': 'isSecureSiteEnabled', 'type': 'bool'},
'is_block_user_upload_enabled': {'key': 'isBlockUserUploadEnabled', 'type': 'bool'},
'trusted_origins': {'key': 'trustedOrigins', 'type': '[str]'},
'site_id': {'key': 'siteId', 'type': 'str'},
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
'key2': {'key': 'key2', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
'is_webchat_preview_enabled': {'key': 'isWebchatPreviewEnabled', 'type': 'bool'},
'is_token_enabled': {'key': 'isTokenEnabled', 'type': 'bool'},
'e_tag': {'key': 'eTag', 'type': 'str'},
}
def __init__(
self,
*,
is_v1_enabled: bool,
is_v3_enabled: bool,
site_name: str,
is_enabled: bool,
is_webchat_preview_enabled: bool,
is_secure_site_enabled: Optional[bool] = None,
is_block_user_upload_enabled: Optional[bool] = None,
trusted_origins: Optional[List[str]] = None,
is_token_enabled: Optional[bool] = None,
e_tag: Optional[str] = None,
**kwargs
):
"""
:keyword is_v1_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v1_enabled: bool
:keyword is_v3_enabled: Required. Whether this site is enabled for Bot Framework V1 protocol.
:paramtype is_v3_enabled: bool
:keyword is_secure_site_enabled: Whether this site is enabled for authentication with Bot
Framework.
:paramtype is_secure_site_enabled: bool
:keyword is_block_user_upload_enabled: Whether this site is enabled for block user upload.
:paramtype is_block_user_upload_enabled: bool
:keyword trusted_origins: List of Trusted Origin URLs for this site. This field is applicable
only if isSecureSiteEnabled is True.
:paramtype trusted_origins: list[str]
:keyword site_name: Required. Site name.
:paramtype site_name: str
:keyword is_enabled: Required. Whether this site is enabled for DirectLine channel.
:paramtype is_enabled: bool
:keyword is_webchat_preview_enabled: Required. Whether this site is enabled for preview
versions of Webchat.
:paramtype is_webchat_preview_enabled: bool
:keyword is_token_enabled: Whether this site is token enabled for channel.
:paramtype is_token_enabled: bool
:keyword e_tag: Entity Tag.
:paramtype e_tag: str
"""
super(Site, self).__init__(site_name=site_name, is_enabled=is_enabled, is_webchat_preview_enabled=is_webchat_preview_enabled, is_v1_enabled=is_v1_enabled, is_v3_enabled=is_v3_enabled, is_secure_site_enabled=is_secure_site_enabled, is_block_user_upload_enabled=is_block_user_upload_enabled, trusted_origins=trusted_origins, **kwargs)
self.is_v1_enabled = is_v1_enabled
self.is_v3_enabled = is_v3_enabled
self.is_secure_site_enabled = is_secure_site_enabled
self.is_block_user_upload_enabled = is_block_user_upload_enabled
self.trusted_origins = trusted_origins
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
self.site_id = None
self.site_name = site_name
self.key = None
self.key2 = None
self.is_enabled = is_enabled
self.is_webchat_preview_enabled = is_webchat_preview_enabled
self.is_token_enabled = is_token_enabled
self.e_tag = e_tag
class SiteInfo(msrest.serialization.Model):
"""Site information for WebChat or DirectLine Channels to identify which site to regenerate keys for.
All required parameters must be populated in order to send to Azure.
:ivar site_name: Required. The site name.
:vartype site_name: str
:ivar key: Required. Determines which key is to be regenerated. Possible values include:
"key1", "key2".
:vartype key: str or ~azure.mgmt.botservice.models.Key
"""
_validation = {
'site_name': {'required': True},
'key': {'required': True},
}
_attribute_map = {
'site_name': {'key': 'siteName', 'type': 'str'},
'key': {'key': 'key', 'type': 'str'},
}
def __init__(
self,
*,
site_name: str,
key: Union[str, "Key"],
**kwargs
):
"""
:keyword site_name: Required. The site name.
:paramtype site_name: str
:keyword key: Required. Determines which key is to be regenerated. Possible values include:
"key1", "key2".
:paramtype key: str or ~azure.mgmt.botservice.models.Key
"""
super(SiteInfo, self).__init__(**kwargs)
self.site_name = site_name
self.key = key
class Sku(msrest.serialization.Model):
"""The SKU of the cognitive services account.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar name: Required. The sku name. Possible values include: "F0", "S1".
:vartype name: str or ~azure.mgmt.botservice.models.SkuName
:ivar tier: Gets the sku tier. This is based on the SKU name. Possible values include: "Free",
"Standard".
:vartype tier: str or ~azure.mgmt.botservice.models.SkuTier
"""
_validation = {
'name': {'required': True},
'tier': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
}
def __init__(
self,
*,
name: Union[str, "SkuName"],
**kwargs
):
"""
:keyword name: Required. The sku name. Possible values include: "F0", "S1".
:paramtype name: str or ~azure.mgmt.botservice.models.SkuName
"""
super(Sku, self).__init__(**kwargs)
self.name = name
self.tier = None
class SkypeChannel(Channel):
"""Skype channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Skype channel resource.
:vartype properties: ~azure.mgmt.botservice.models.SkypeChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'SkypeChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["SkypeChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Skype channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.SkypeChannelProperties
"""
super(SkypeChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'SkypeChannel' # type: str
self.properties = properties
class SkypeChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Microsoft Teams channel.
All required parameters must be populated in order to send to Azure.
:ivar enable_messaging: Enable messaging for Skype channel.
:vartype enable_messaging: bool
:ivar enable_media_cards: Enable media cards for Skype channel.
:vartype enable_media_cards: bool
:ivar enable_video: Enable video for Skype channel.
:vartype enable_video: bool
:ivar enable_calling: Enable calling for Skype channel.
:vartype enable_calling: bool
:ivar enable_screen_sharing: Enable screen sharing for Skype channel.
:vartype enable_screen_sharing: bool
:ivar enable_groups: Enable groups for Skype channel.
:vartype enable_groups: bool
:ivar groups_mode: Group mode for Skype channel.
:vartype groups_mode: str
:ivar calling_web_hook: Calling web hook for Skype channel.
:vartype calling_web_hook: str
:ivar incoming_call_route: Incoming call route for Skype channel.
:vartype incoming_call_route: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'is_enabled': {'required': True},
}
_attribute_map = {
'enable_messaging': {'key': 'enableMessaging', 'type': 'bool'},
'enable_media_cards': {'key': 'enableMediaCards', 'type': 'bool'},
'enable_video': {'key': 'enableVideo', 'type': 'bool'},
'enable_calling': {'key': 'enableCalling', 'type': 'bool'},
'enable_screen_sharing': {'key': 'enableScreenSharing', 'type': 'bool'},
'enable_groups': {'key': 'enableGroups', 'type': 'bool'},
'groups_mode': {'key': 'groupsMode', 'type': 'str'},
'calling_web_hook': {'key': 'callingWebHook', 'type': 'str'},
'incoming_call_route': {'key': 'incomingCallRoute', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
enable_messaging: Optional[bool] = None,
enable_media_cards: Optional[bool] = None,
enable_video: Optional[bool] = None,
enable_calling: Optional[bool] = None,
enable_screen_sharing: Optional[bool] = None,
enable_groups: Optional[bool] = None,
groups_mode: Optional[str] = None,
calling_web_hook: Optional[str] = None,
incoming_call_route: Optional[str] = None,
**kwargs
):
"""
:keyword enable_messaging: Enable messaging for Skype channel.
:paramtype enable_messaging: bool
:keyword enable_media_cards: Enable media cards for Skype channel.
:paramtype enable_media_cards: bool
:keyword enable_video: Enable video for Skype channel.
:paramtype enable_video: bool
:keyword enable_calling: Enable calling for Skype channel.
:paramtype enable_calling: bool
:keyword enable_screen_sharing: Enable screen sharing for Skype channel.
:paramtype enable_screen_sharing: bool
:keyword enable_groups: Enable groups for Skype channel.
:paramtype enable_groups: bool
:keyword groups_mode: Group mode for Skype channel.
:paramtype groups_mode: str
:keyword calling_web_hook: Calling web hook for Skype channel.
:paramtype calling_web_hook: str
:keyword incoming_call_route: Incoming call route for Skype channel.
:paramtype incoming_call_route: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(SkypeChannelProperties, self).__init__(**kwargs)
self.enable_messaging = enable_messaging
self.enable_media_cards = enable_media_cards
self.enable_video = enable_video
self.enable_calling = enable_calling
self.enable_screen_sharing = enable_screen_sharing
self.enable_groups = enable_groups
self.groups_mode = groups_mode
self.calling_web_hook = calling_web_hook
self.incoming_call_route = incoming_call_route
self.is_enabled = is_enabled
class SlackChannel(Channel):
"""Slack channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Slack channel resource.
:vartype properties: ~azure.mgmt.botservice.models.SlackChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'SlackChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["SlackChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Slack channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.SlackChannelProperties
"""
super(SlackChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'SlackChannel' # type: str
self.properties = properties
class SlackChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Slack channel.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar client_id: The Slack client id.
:vartype client_id: str
:ivar client_secret: The Slack client secret. Value only returned through POST to the action
Channel List API, otherwise empty.
:vartype client_secret: str
:ivar verification_token: The Slack verification token. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype verification_token: str
:ivar scopes: The Slack permission scopes.
:vartype scopes: str
:ivar landing_page_url: The Slack landing page Url.
:vartype landing_page_url: str
:ivar redirect_action: The Slack redirect action.
:vartype redirect_action: str
:ivar last_submission_id: The Sms auth token.
:vartype last_submission_id: str
:ivar register_before_o_auth_flow: Whether to register the settings before OAuth validation is
performed. Recommended to True.
:vartype register_before_o_auth_flow: bool
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar signing_secret: The Slack signing secret.
:vartype signing_secret: str
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'redirect_action': {'readonly': True},
'last_submission_id': {'readonly': True},
'register_before_o_auth_flow': {'readonly': True},
'is_validated': {'readonly': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'client_id': {'key': 'clientId', 'type': 'str'},
'client_secret': {'key': 'clientSecret', 'type': 'str'},
'verification_token': {'key': 'verificationToken', 'type': 'str'},
'scopes': {'key': 'scopes', 'type': 'str'},
'landing_page_url': {'key': 'landingPageUrl', 'type': 'str'},
'redirect_action': {'key': 'redirectAction', 'type': 'str'},
'last_submission_id': {'key': 'lastSubmissionId', 'type': 'str'},
'register_before_o_auth_flow': {'key': 'registerBeforeOAuthFlow', 'type': 'bool'},
'is_validated': {'key': 'IsValidated', 'type': 'bool'},
'signing_secret': {'key': 'signingSecret', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
verification_token: Optional[str] = None,
scopes: Optional[str] = None,
landing_page_url: Optional[str] = None,
signing_secret: Optional[str] = None,
**kwargs
):
"""
:keyword client_id: The Slack client id.
:paramtype client_id: str
:keyword client_secret: The Slack client secret. Value only returned through POST to the action
Channel List API, otherwise empty.
:paramtype client_secret: str
:keyword verification_token: The Slack verification token. Value only returned through POST to
the action Channel List API, otherwise empty.
:paramtype verification_token: str
:keyword scopes: The Slack permission scopes.
:paramtype scopes: str
:keyword landing_page_url: The Slack landing page Url.
:paramtype landing_page_url: str
:keyword signing_secret: The Slack signing secret.
:paramtype signing_secret: str
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(SlackChannelProperties, self).__init__(**kwargs)
self.client_id = client_id
self.client_secret = client_secret
self.verification_token = verification_token
self.scopes = scopes
self.landing_page_url = landing_page_url
self.redirect_action = None
self.last_submission_id = None
self.register_before_o_auth_flow = None
self.is_validated = None
self.signing_secret = signing_secret
self.is_enabled = is_enabled
class SmsChannel(Channel):
"""Sms channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Sms channel resource.
:vartype properties: ~azure.mgmt.botservice.models.SmsChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'SmsChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["SmsChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Sms channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.SmsChannelProperties
"""
super(SmsChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'SmsChannel' # type: str
self.properties = properties
class SmsChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Sms channel.
All required parameters must be populated in order to send to Azure.
:ivar phone: Required. The Sms phone.
:vartype phone: str
:ivar account_sid: Required. The Sms account SID. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype account_sid: str
:ivar auth_token: The Sms auth token. Value only returned through POST to the action Channel
List API, otherwise empty.
:vartype auth_token: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'phone': {'required': True},
'account_sid': {'required': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'phone': {'key': 'phone', 'type': 'str'},
'account_sid': {'key': 'accountSID', 'type': 'str'},
'auth_token': {'key': 'authToken', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
phone: str,
account_sid: str,
is_enabled: bool,
auth_token: Optional[str] = None,
is_validated: Optional[bool] = None,
**kwargs
):
"""
:keyword phone: Required. The Sms phone.
:paramtype phone: str
:keyword account_sid: Required. The Sms account SID. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype account_sid: str
:keyword auth_token: The Sms auth token. Value only returned through POST to the action Channel
List API, otherwise empty.
:paramtype auth_token: str
:keyword is_validated: Whether this channel is validated for the bot.
:paramtype is_validated: bool
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(SmsChannelProperties, self).__init__(**kwargs)
self.phone = phone
self.account_sid = account_sid
self.auth_token = auth_token
self.is_validated = is_validated
self.is_enabled = is_enabled
class TelegramChannel(Channel):
"""Telegram channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Telegram channel resource.
:vartype properties: ~azure.mgmt.botservice.models.TelegramChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'TelegramChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["TelegramChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Telegram channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.TelegramChannelProperties
"""
super(TelegramChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'TelegramChannel' # type: str
self.properties = properties
class TelegramChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Telegram channel.
All required parameters must be populated in order to send to Azure.
:ivar access_token: The Telegram access token. Value only returned through POST to the action
Channel List API, otherwise empty.
:vartype access_token: str
:ivar is_validated: Whether this channel is validated for the bot.
:vartype is_validated: bool
:ivar is_enabled: Required. Whether this channel is enabled for the bot.
:vartype is_enabled: bool
"""
_validation = {
'is_enabled': {'required': True},
}
_attribute_map = {
'access_token': {'key': 'accessToken', 'type': 'str'},
'is_validated': {'key': 'isValidated', 'type': 'bool'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(
self,
*,
is_enabled: bool,
access_token: Optional[str] = None,
is_validated: Optional[bool] = None,
**kwargs
):
"""
:keyword access_token: The Telegram access token. Value only returned through POST to the
action Channel List API, otherwise empty.
:paramtype access_token: str
:keyword is_validated: Whether this channel is validated for the bot.
:paramtype is_validated: bool
:keyword is_enabled: Required. Whether this channel is enabled for the bot.
:paramtype is_enabled: bool
"""
super(TelegramChannelProperties, self).__init__(**kwargs)
self.access_token = access_token
self.is_validated = is_validated
self.is_enabled = is_enabled
class WebChatChannel(Channel):
"""Web Chat channel definition.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar channel_name: Required. The channel name.Constant filled by server.
:vartype channel_name: str
:ivar etag: Entity Tag of the resource.
:vartype etag: str
:ivar provisioning_state: Provisioning state of the resource.
:vartype provisioning_state: str
:ivar location: Specifies the location of the resource.
:vartype location: str
:ivar properties: The set of properties specific to Web Chat channel resource.
:vartype properties: ~azure.mgmt.botservice.models.WebChatChannelProperties
"""
_validation = {
'channel_name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'channel_name': {'key': 'channelName', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'WebChatChannelProperties'},
}
def __init__(
self,
*,
etag: Optional[str] = None,
location: Optional[str] = "global",
properties: Optional["WebChatChannelProperties"] = None,
**kwargs
):
"""
:keyword etag: Entity Tag of the resource.
:paramtype etag: str
:keyword location: Specifies the location of the resource.
:paramtype location: str
:keyword properties: The set of properties specific to Web Chat channel resource.
:paramtype properties: ~azure.mgmt.botservice.models.WebChatChannelProperties
"""
super(WebChatChannel, self).__init__(etag=etag, location=location, **kwargs)
self.channel_name = 'WebChatChannel' # type: str
self.properties = properties
class WebChatChannelProperties(msrest.serialization.Model):
"""The parameters to provide for the Web Chat channel.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar web_chat_embed_code: Web chat control embed code.
:vartype web_chat_embed_code: str
:ivar sites: The list of Web Chat sites.
:vartype sites: list[~azure.mgmt.botservice.models.WebChatSite]
"""
_validation = {
'web_chat_embed_code': {'readonly': True},
}
_attribute_map = {
'web_chat_embed_code': {'key': 'webChatEmbedCode', 'type': 'str'},
'sites': {'key': 'sites', 'type': '[WebChatSite]'},
}
def __init__(
self,
*,
sites: Optional[List["WebChatSite"]] = None,
**kwargs
):
"""
:keyword sites: The list of Web Chat sites.
:paramtype sites: list[~azure.mgmt.botservice.models.WebChatSite]
"""
super(WebChatChannelProperties, self).__init__(**kwargs)
self.web_chat_embed_code = None
self.sites = sites
| 0.935626 | 0.166845 |
from enum import Enum
from six import with_metaclass
from azure.core import CaseInsensitiveEnumMeta
class ChannelName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
ALEXA_CHANNEL = "AlexaChannel"
FACEBOOK_CHANNEL = "FacebookChannel"
EMAIL_CHANNEL = "EmailChannel"
KIK_CHANNEL = "KikChannel"
TELEGRAM_CHANNEL = "TelegramChannel"
SLACK_CHANNEL = "SlackChannel"
MS_TEAMS_CHANNEL = "MsTeamsChannel"
SKYPE_CHANNEL = "SkypeChannel"
WEB_CHAT_CHANNEL = "WebChatChannel"
DIRECT_LINE_CHANNEL = "DirectLineChannel"
SMS_CHANNEL = "SmsChannel"
LINE_CHANNEL = "LineChannel"
DIRECT_LINE_SPEECH_CHANNEL = "DirectLineSpeechChannel"
OUTLOOK_CHANNEL = "OutlookChannel"
class Key(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Determines which key is to be regenerated
"""
KEY1 = "key1"
KEY2 = "key2"
class Kind(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Indicates the type of bot service
"""
SDK = "sdk"
DESIGNER = "designer"
BOT = "bot"
FUNCTION = "function"
AZUREBOT = "azurebot"
class MsaAppType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Microsoft App Type for the bot
"""
USER_ASSIGNED_MSI = "UserAssignedMSI"
SINGLE_TENANT = "SingleTenant"
MULTI_TENANT = "MultiTenant"
class OperationResultStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The status of the operation being performed.
"""
CANCELED = "Canceled"
SUCCEEDED = "Succeeded"
FAILED = "Failed"
REQUESTED = "Requested"
RUNNING = "Running"
class PrivateEndpointConnectionProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The current provisioning state.
"""
SUCCEEDED = "Succeeded"
CREATING = "Creating"
DELETING = "Deleting"
FAILED = "Failed"
class PrivateEndpointServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The private endpoint connection status.
"""
PENDING = "Pending"
APPROVED = "Approved"
REJECTED = "Rejected"
class PublicNetworkAccess(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Whether the bot is in an isolated network
"""
ENABLED = "Enabled"
DISABLED = "Disabled"
class RegenerateKeysChannelName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
WEB_CHAT_CHANNEL = "WebChatChannel"
DIRECT_LINE_CHANNEL = "DirectLineChannel"
class SkuName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The name of SKU.
"""
F0 = "F0"
S1 = "S1"
class SkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Gets the sku tier. This is based on the SKU name.
"""
FREE = "Free"
STANDARD = "Standard"
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/models/_azure_bot_service_enums.py
|
_azure_bot_service_enums.py
|
from enum import Enum
from six import with_metaclass
from azure.core import CaseInsensitiveEnumMeta
class ChannelName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
ALEXA_CHANNEL = "AlexaChannel"
FACEBOOK_CHANNEL = "FacebookChannel"
EMAIL_CHANNEL = "EmailChannel"
KIK_CHANNEL = "KikChannel"
TELEGRAM_CHANNEL = "TelegramChannel"
SLACK_CHANNEL = "SlackChannel"
MS_TEAMS_CHANNEL = "MsTeamsChannel"
SKYPE_CHANNEL = "SkypeChannel"
WEB_CHAT_CHANNEL = "WebChatChannel"
DIRECT_LINE_CHANNEL = "DirectLineChannel"
SMS_CHANNEL = "SmsChannel"
LINE_CHANNEL = "LineChannel"
DIRECT_LINE_SPEECH_CHANNEL = "DirectLineSpeechChannel"
OUTLOOK_CHANNEL = "OutlookChannel"
class Key(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Determines which key is to be regenerated
"""
KEY1 = "key1"
KEY2 = "key2"
class Kind(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Indicates the type of bot service
"""
SDK = "sdk"
DESIGNER = "designer"
BOT = "bot"
FUNCTION = "function"
AZUREBOT = "azurebot"
class MsaAppType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Microsoft App Type for the bot
"""
USER_ASSIGNED_MSI = "UserAssignedMSI"
SINGLE_TENANT = "SingleTenant"
MULTI_TENANT = "MultiTenant"
class OperationResultStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The status of the operation being performed.
"""
CANCELED = "Canceled"
SUCCEEDED = "Succeeded"
FAILED = "Failed"
REQUESTED = "Requested"
RUNNING = "Running"
class PrivateEndpointConnectionProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The current provisioning state.
"""
SUCCEEDED = "Succeeded"
CREATING = "Creating"
DELETING = "Deleting"
FAILED = "Failed"
class PrivateEndpointServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The private endpoint connection status.
"""
PENDING = "Pending"
APPROVED = "Approved"
REJECTED = "Rejected"
class PublicNetworkAccess(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Whether the bot is in an isolated network
"""
ENABLED = "Enabled"
DISABLED = "Disabled"
class RegenerateKeysChannelName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
WEB_CHAT_CHANNEL = "WebChatChannel"
DIRECT_LINE_CHANNEL = "DirectLineChannel"
class SkuName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The name of SKU.
"""
F0 = "F0"
S1 = "S1"
class SkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Gets the sku tier. This is based on the SKU name.
"""
FREE = "Free"
STANDARD = "Standard"
| 0.455441 | 0.084078 |
from ._models_py3 import AlexaChannel
from ._models_py3 import AlexaChannelProperties
from ._models_py3 import Bot
from ._models_py3 import BotChannel
from ._models_py3 import BotProperties
from ._models_py3 import BotResponseList
from ._models_py3 import Channel
from ._models_py3 import ChannelResponseList
from ._models_py3 import ChannelSettings
from ._models_py3 import CheckNameAvailabilityRequestBody
from ._models_py3 import CheckNameAvailabilityResponseBody
from ._models_py3 import ConnectionItemName
from ._models_py3 import ConnectionSetting
from ._models_py3 import ConnectionSettingParameter
from ._models_py3 import ConnectionSettingProperties
from ._models_py3 import ConnectionSettingResponseList
from ._models_py3 import DirectLineChannel
from ._models_py3 import DirectLineChannelProperties
from ._models_py3 import DirectLineSite
from ._models_py3 import DirectLineSpeechChannel
from ._models_py3 import DirectLineSpeechChannelProperties
from ._models_py3 import EmailChannel
from ._models_py3 import EmailChannelProperties
from ._models_py3 import Error
from ._models_py3 import ErrorBody
from ._models_py3 import FacebookChannel
from ._models_py3 import FacebookChannelProperties
from ._models_py3 import FacebookPage
from ._models_py3 import HostSettingsResponse
from ._models_py3 import KikChannel
from ._models_py3 import KikChannelProperties
from ._models_py3 import LineChannel
from ._models_py3 import LineChannelProperties
from ._models_py3 import LineRegistration
from ._models_py3 import ListChannelWithKeysResponse
from ._models_py3 import MsTeamsChannel
from ._models_py3 import MsTeamsChannelProperties
from ._models_py3 import OperationDisplayInfo
from ._models_py3 import OperationEntity
from ._models_py3 import OperationEntityListResult
from ._models_py3 import OperationResultsDescription
from ._models_py3 import PrivateEndpoint
from ._models_py3 import PrivateEndpointConnection
from ._models_py3 import PrivateEndpointConnectionListResult
from ._models_py3 import PrivateLinkResource
from ._models_py3 import PrivateLinkResourceBase
from ._models_py3 import PrivateLinkResourceListResult
from ._models_py3 import PrivateLinkServiceConnectionState
from ._models_py3 import Resource
from ._models_py3 import ServiceProvider
from ._models_py3 import ServiceProviderParameter
from ._models_py3 import ServiceProviderParameterMetadata
from ._models_py3 import ServiceProviderParameterMetadataConstraints
from ._models_py3 import ServiceProviderProperties
from ._models_py3 import ServiceProviderResponseList
from ._models_py3 import Site
from ._models_py3 import SiteInfo
from ._models_py3 import Sku
from ._models_py3 import SkypeChannel
from ._models_py3 import SkypeChannelProperties
from ._models_py3 import SlackChannel
from ._models_py3 import SlackChannelProperties
from ._models_py3 import SmsChannel
from ._models_py3 import SmsChannelProperties
from ._models_py3 import TelegramChannel
from ._models_py3 import TelegramChannelProperties
from ._models_py3 import WebChatChannel
from ._models_py3 import WebChatChannelProperties
from ._models_py3 import WebChatSite
from ._azure_bot_service_enums import (
ChannelName,
Key,
Kind,
MsaAppType,
OperationResultStatus,
PrivateEndpointConnectionProvisioningState,
PrivateEndpointServiceConnectionStatus,
PublicNetworkAccess,
RegenerateKeysChannelName,
SkuName,
SkuTier,
)
__all__ = [
'AlexaChannel',
'AlexaChannelProperties',
'Bot',
'BotChannel',
'BotProperties',
'BotResponseList',
'Channel',
'ChannelResponseList',
'ChannelSettings',
'CheckNameAvailabilityRequestBody',
'CheckNameAvailabilityResponseBody',
'ConnectionItemName',
'ConnectionSetting',
'ConnectionSettingParameter',
'ConnectionSettingProperties',
'ConnectionSettingResponseList',
'DirectLineChannel',
'DirectLineChannelProperties',
'DirectLineSite',
'DirectLineSpeechChannel',
'DirectLineSpeechChannelProperties',
'EmailChannel',
'EmailChannelProperties',
'Error',
'ErrorBody',
'FacebookChannel',
'FacebookChannelProperties',
'FacebookPage',
'HostSettingsResponse',
'KikChannel',
'KikChannelProperties',
'LineChannel',
'LineChannelProperties',
'LineRegistration',
'ListChannelWithKeysResponse',
'MsTeamsChannel',
'MsTeamsChannelProperties',
'OperationDisplayInfo',
'OperationEntity',
'OperationEntityListResult',
'OperationResultsDescription',
'PrivateEndpoint',
'PrivateEndpointConnection',
'PrivateEndpointConnectionListResult',
'PrivateLinkResource',
'PrivateLinkResourceBase',
'PrivateLinkResourceListResult',
'PrivateLinkServiceConnectionState',
'Resource',
'ServiceProvider',
'ServiceProviderParameter',
'ServiceProviderParameterMetadata',
'ServiceProviderParameterMetadataConstraints',
'ServiceProviderProperties',
'ServiceProviderResponseList',
'Site',
'SiteInfo',
'Sku',
'SkypeChannel',
'SkypeChannelProperties',
'SlackChannel',
'SlackChannelProperties',
'SmsChannel',
'SmsChannelProperties',
'TelegramChannel',
'TelegramChannelProperties',
'WebChatChannel',
'WebChatChannelProperties',
'WebChatSite',
'ChannelName',
'Key',
'Kind',
'MsaAppType',
'OperationResultStatus',
'PrivateEndpointConnectionProvisioningState',
'PrivateEndpointServiceConnectionStatus',
'PublicNetworkAccess',
'RegenerateKeysChannelName',
'SkuName',
'SkuTier',
]
|
azure-mgmt-botservice
|
/azure_mgmt_botservice-2.0.0b3-py3-none-any.whl/azure/mgmt/botservice/models/__init__.py
|
__init__.py
|
from ._models_py3 import AlexaChannel
from ._models_py3 import AlexaChannelProperties
from ._models_py3 import Bot
from ._models_py3 import BotChannel
from ._models_py3 import BotProperties
from ._models_py3 import BotResponseList
from ._models_py3 import Channel
from ._models_py3 import ChannelResponseList
from ._models_py3 import ChannelSettings
from ._models_py3 import CheckNameAvailabilityRequestBody
from ._models_py3 import CheckNameAvailabilityResponseBody
from ._models_py3 import ConnectionItemName
from ._models_py3 import ConnectionSetting
from ._models_py3 import ConnectionSettingParameter
from ._models_py3 import ConnectionSettingProperties
from ._models_py3 import ConnectionSettingResponseList
from ._models_py3 import DirectLineChannel
from ._models_py3 import DirectLineChannelProperties
from ._models_py3 import DirectLineSite
from ._models_py3 import DirectLineSpeechChannel
from ._models_py3 import DirectLineSpeechChannelProperties
from ._models_py3 import EmailChannel
from ._models_py3 import EmailChannelProperties
from ._models_py3 import Error
from ._models_py3 import ErrorBody
from ._models_py3 import FacebookChannel
from ._models_py3 import FacebookChannelProperties
from ._models_py3 import FacebookPage
from ._models_py3 import HostSettingsResponse
from ._models_py3 import KikChannel
from ._models_py3 import KikChannelProperties
from ._models_py3 import LineChannel
from ._models_py3 import LineChannelProperties
from ._models_py3 import LineRegistration
from ._models_py3 import ListChannelWithKeysResponse
from ._models_py3 import MsTeamsChannel
from ._models_py3 import MsTeamsChannelProperties
from ._models_py3 import OperationDisplayInfo
from ._models_py3 import OperationEntity
from ._models_py3 import OperationEntityListResult
from ._models_py3 import OperationResultsDescription
from ._models_py3 import PrivateEndpoint
from ._models_py3 import PrivateEndpointConnection
from ._models_py3 import PrivateEndpointConnectionListResult
from ._models_py3 import PrivateLinkResource
from ._models_py3 import PrivateLinkResourceBase
from ._models_py3 import PrivateLinkResourceListResult
from ._models_py3 import PrivateLinkServiceConnectionState
from ._models_py3 import Resource
from ._models_py3 import ServiceProvider
from ._models_py3 import ServiceProviderParameter
from ._models_py3 import ServiceProviderParameterMetadata
from ._models_py3 import ServiceProviderParameterMetadataConstraints
from ._models_py3 import ServiceProviderProperties
from ._models_py3 import ServiceProviderResponseList
from ._models_py3 import Site
from ._models_py3 import SiteInfo
from ._models_py3 import Sku
from ._models_py3 import SkypeChannel
from ._models_py3 import SkypeChannelProperties
from ._models_py3 import SlackChannel
from ._models_py3 import SlackChannelProperties
from ._models_py3 import SmsChannel
from ._models_py3 import SmsChannelProperties
from ._models_py3 import TelegramChannel
from ._models_py3 import TelegramChannelProperties
from ._models_py3 import WebChatChannel
from ._models_py3 import WebChatChannelProperties
from ._models_py3 import WebChatSite
from ._azure_bot_service_enums import (
ChannelName,
Key,
Kind,
MsaAppType,
OperationResultStatus,
PrivateEndpointConnectionProvisioningState,
PrivateEndpointServiceConnectionStatus,
PublicNetworkAccess,
RegenerateKeysChannelName,
SkuName,
SkuTier,
)
__all__ = [
'AlexaChannel',
'AlexaChannelProperties',
'Bot',
'BotChannel',
'BotProperties',
'BotResponseList',
'Channel',
'ChannelResponseList',
'ChannelSettings',
'CheckNameAvailabilityRequestBody',
'CheckNameAvailabilityResponseBody',
'ConnectionItemName',
'ConnectionSetting',
'ConnectionSettingParameter',
'ConnectionSettingProperties',
'ConnectionSettingResponseList',
'DirectLineChannel',
'DirectLineChannelProperties',
'DirectLineSite',
'DirectLineSpeechChannel',
'DirectLineSpeechChannelProperties',
'EmailChannel',
'EmailChannelProperties',
'Error',
'ErrorBody',
'FacebookChannel',
'FacebookChannelProperties',
'FacebookPage',
'HostSettingsResponse',
'KikChannel',
'KikChannelProperties',
'LineChannel',
'LineChannelProperties',
'LineRegistration',
'ListChannelWithKeysResponse',
'MsTeamsChannel',
'MsTeamsChannelProperties',
'OperationDisplayInfo',
'OperationEntity',
'OperationEntityListResult',
'OperationResultsDescription',
'PrivateEndpoint',
'PrivateEndpointConnection',
'PrivateEndpointConnectionListResult',
'PrivateLinkResource',
'PrivateLinkResourceBase',
'PrivateLinkResourceListResult',
'PrivateLinkServiceConnectionState',
'Resource',
'ServiceProvider',
'ServiceProviderParameter',
'ServiceProviderParameterMetadata',
'ServiceProviderParameterMetadataConstraints',
'ServiceProviderProperties',
'ServiceProviderResponseList',
'Site',
'SiteInfo',
'Sku',
'SkypeChannel',
'SkypeChannelProperties',
'SlackChannel',
'SlackChannelProperties',
'SmsChannel',
'SmsChannelProperties',
'TelegramChannel',
'TelegramChannelProperties',
'WebChatChannel',
'WebChatChannelProperties',
'WebChatSite',
'ChannelName',
'Key',
'Kind',
'MsaAppType',
'OperationResultStatus',
'PrivateEndpointConnectionProvisioningState',
'PrivateEndpointServiceConnectionStatus',
'PublicNetworkAccess',
'RegenerateKeysChannelName',
'SkuName',
'SkuTier',
]
| 0.459561 | 0.069668 |
from copy import deepcopy
from typing import Any, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from . import models
from ._configuration import CdnManagementClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import (
AFDCustomDomainsOperations,
AFDEndpointsOperations,
AFDOriginGroupsOperations,
AFDOriginsOperations,
AFDProfilesOperations,
CdnManagementClientOperationsMixin,
CustomDomainsOperations,
EdgeNodesOperations,
EndpointsOperations,
LogAnalyticsOperations,
ManagedRuleSetsOperations,
Operations,
OriginGroupsOperations,
OriginsOperations,
PoliciesOperations,
ProfilesOperations,
ResourceUsageOperations,
RoutesOperations,
RuleSetsOperations,
RulesOperations,
SecretsOperations,
SecurityPoliciesOperations,
ValidateOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class CdnManagementClient(
CdnManagementClientOperationsMixin
): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes
"""Cdn Management Client.
:ivar afd_profiles: AFDProfilesOperations operations
:vartype afd_profiles: azure.mgmt.cdn.operations.AFDProfilesOperations
:ivar afd_custom_domains: AFDCustomDomainsOperations operations
:vartype afd_custom_domains: azure.mgmt.cdn.operations.AFDCustomDomainsOperations
:ivar afd_endpoints: AFDEndpointsOperations operations
:vartype afd_endpoints: azure.mgmt.cdn.operations.AFDEndpointsOperations
:ivar afd_origin_groups: AFDOriginGroupsOperations operations
:vartype afd_origin_groups: azure.mgmt.cdn.operations.AFDOriginGroupsOperations
:ivar afd_origins: AFDOriginsOperations operations
:vartype afd_origins: azure.mgmt.cdn.operations.AFDOriginsOperations
:ivar routes: RoutesOperations operations
:vartype routes: azure.mgmt.cdn.operations.RoutesOperations
:ivar rule_sets: RuleSetsOperations operations
:vartype rule_sets: azure.mgmt.cdn.operations.RuleSetsOperations
:ivar rules: RulesOperations operations
:vartype rules: azure.mgmt.cdn.operations.RulesOperations
:ivar security_policies: SecurityPoliciesOperations operations
:vartype security_policies: azure.mgmt.cdn.operations.SecurityPoliciesOperations
:ivar secrets: SecretsOperations operations
:vartype secrets: azure.mgmt.cdn.operations.SecretsOperations
:ivar validate: ValidateOperations operations
:vartype validate: azure.mgmt.cdn.operations.ValidateOperations
:ivar log_analytics: LogAnalyticsOperations operations
:vartype log_analytics: azure.mgmt.cdn.operations.LogAnalyticsOperations
:ivar profiles: ProfilesOperations operations
:vartype profiles: azure.mgmt.cdn.operations.ProfilesOperations
:ivar endpoints: EndpointsOperations operations
:vartype endpoints: azure.mgmt.cdn.operations.EndpointsOperations
:ivar origins: OriginsOperations operations
:vartype origins: azure.mgmt.cdn.operations.OriginsOperations
:ivar origin_groups: OriginGroupsOperations operations
:vartype origin_groups: azure.mgmt.cdn.operations.OriginGroupsOperations
:ivar custom_domains: CustomDomainsOperations operations
:vartype custom_domains: azure.mgmt.cdn.operations.CustomDomainsOperations
:ivar resource_usage: ResourceUsageOperations operations
:vartype resource_usage: azure.mgmt.cdn.operations.ResourceUsageOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.cdn.operations.Operations
:ivar edge_nodes: EdgeNodesOperations operations
:vartype edge_nodes: azure.mgmt.cdn.operations.EdgeNodesOperations
:ivar policies: PoliciesOperations operations
:vartype policies: azure.mgmt.cdn.operations.PoliciesOperations
:ivar managed_rule_sets: ManagedRuleSetsOperations operations
:vartype managed_rule_sets: azure.mgmt.cdn.operations.ManagedRuleSetsOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = CdnManagementClientConfiguration(
credential=credential, subscription_id=subscription_id, **kwargs
)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.afd_profiles = AFDProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_custom_domains = AFDCustomDomainsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_endpoints = AFDEndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_origin_groups = AFDOriginGroupsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_origins = AFDOriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.routes = RoutesOperations(self._client, self._config, self._serialize, self._deserialize)
self.rule_sets = RuleSetsOperations(self._client, self._config, self._serialize, self._deserialize)
self.rules = RulesOperations(self._client, self._config, self._serialize, self._deserialize)
self.security_policies = SecurityPoliciesOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.secrets = SecretsOperations(self._client, self._config, self._serialize, self._deserialize)
self.validate = ValidateOperations(self._client, self._config, self._serialize, self._deserialize)
self.log_analytics = LogAnalyticsOperations(self._client, self._config, self._serialize, self._deserialize)
self.profiles = ProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.endpoints = EndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origins = OriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origin_groups = OriginGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.custom_domains = CustomDomainsOperations(self._client, self._config, self._serialize, self._deserialize)
self.resource_usage = ResourceUsageOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.edge_nodes = EdgeNodesOperations(self._client, self._config, self._serialize, self._deserialize)
self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize)
self.managed_rule_sets = ManagedRuleSetsOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self):
# type: () -> None
self._client.close()
def __enter__(self):
# type: () -> CdnManagementClient
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/_cdn_management_client.py
|
_cdn_management_client.py
|
from copy import deepcopy
from typing import Any, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from . import models
from ._configuration import CdnManagementClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import (
AFDCustomDomainsOperations,
AFDEndpointsOperations,
AFDOriginGroupsOperations,
AFDOriginsOperations,
AFDProfilesOperations,
CdnManagementClientOperationsMixin,
CustomDomainsOperations,
EdgeNodesOperations,
EndpointsOperations,
LogAnalyticsOperations,
ManagedRuleSetsOperations,
Operations,
OriginGroupsOperations,
OriginsOperations,
PoliciesOperations,
ProfilesOperations,
ResourceUsageOperations,
RoutesOperations,
RuleSetsOperations,
RulesOperations,
SecretsOperations,
SecurityPoliciesOperations,
ValidateOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class CdnManagementClient(
CdnManagementClientOperationsMixin
): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes
"""Cdn Management Client.
:ivar afd_profiles: AFDProfilesOperations operations
:vartype afd_profiles: azure.mgmt.cdn.operations.AFDProfilesOperations
:ivar afd_custom_domains: AFDCustomDomainsOperations operations
:vartype afd_custom_domains: azure.mgmt.cdn.operations.AFDCustomDomainsOperations
:ivar afd_endpoints: AFDEndpointsOperations operations
:vartype afd_endpoints: azure.mgmt.cdn.operations.AFDEndpointsOperations
:ivar afd_origin_groups: AFDOriginGroupsOperations operations
:vartype afd_origin_groups: azure.mgmt.cdn.operations.AFDOriginGroupsOperations
:ivar afd_origins: AFDOriginsOperations operations
:vartype afd_origins: azure.mgmt.cdn.operations.AFDOriginsOperations
:ivar routes: RoutesOperations operations
:vartype routes: azure.mgmt.cdn.operations.RoutesOperations
:ivar rule_sets: RuleSetsOperations operations
:vartype rule_sets: azure.mgmt.cdn.operations.RuleSetsOperations
:ivar rules: RulesOperations operations
:vartype rules: azure.mgmt.cdn.operations.RulesOperations
:ivar security_policies: SecurityPoliciesOperations operations
:vartype security_policies: azure.mgmt.cdn.operations.SecurityPoliciesOperations
:ivar secrets: SecretsOperations operations
:vartype secrets: azure.mgmt.cdn.operations.SecretsOperations
:ivar validate: ValidateOperations operations
:vartype validate: azure.mgmt.cdn.operations.ValidateOperations
:ivar log_analytics: LogAnalyticsOperations operations
:vartype log_analytics: azure.mgmt.cdn.operations.LogAnalyticsOperations
:ivar profiles: ProfilesOperations operations
:vartype profiles: azure.mgmt.cdn.operations.ProfilesOperations
:ivar endpoints: EndpointsOperations operations
:vartype endpoints: azure.mgmt.cdn.operations.EndpointsOperations
:ivar origins: OriginsOperations operations
:vartype origins: azure.mgmt.cdn.operations.OriginsOperations
:ivar origin_groups: OriginGroupsOperations operations
:vartype origin_groups: azure.mgmt.cdn.operations.OriginGroupsOperations
:ivar custom_domains: CustomDomainsOperations operations
:vartype custom_domains: azure.mgmt.cdn.operations.CustomDomainsOperations
:ivar resource_usage: ResourceUsageOperations operations
:vartype resource_usage: azure.mgmt.cdn.operations.ResourceUsageOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.cdn.operations.Operations
:ivar edge_nodes: EdgeNodesOperations operations
:vartype edge_nodes: azure.mgmt.cdn.operations.EdgeNodesOperations
:ivar policies: PoliciesOperations operations
:vartype policies: azure.mgmt.cdn.operations.PoliciesOperations
:ivar managed_rule_sets: ManagedRuleSetsOperations operations
:vartype managed_rule_sets: azure.mgmt.cdn.operations.ManagedRuleSetsOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = CdnManagementClientConfiguration(
credential=credential, subscription_id=subscription_id, **kwargs
)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.afd_profiles = AFDProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_custom_domains = AFDCustomDomainsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_endpoints = AFDEndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_origin_groups = AFDOriginGroupsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_origins = AFDOriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.routes = RoutesOperations(self._client, self._config, self._serialize, self._deserialize)
self.rule_sets = RuleSetsOperations(self._client, self._config, self._serialize, self._deserialize)
self.rules = RulesOperations(self._client, self._config, self._serialize, self._deserialize)
self.security_policies = SecurityPoliciesOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.secrets = SecretsOperations(self._client, self._config, self._serialize, self._deserialize)
self.validate = ValidateOperations(self._client, self._config, self._serialize, self._deserialize)
self.log_analytics = LogAnalyticsOperations(self._client, self._config, self._serialize, self._deserialize)
self.profiles = ProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.endpoints = EndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origins = OriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origin_groups = OriginGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.custom_domains = CustomDomainsOperations(self._client, self._config, self._serialize, self._deserialize)
self.resource_usage = ResourceUsageOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.edge_nodes = EdgeNodesOperations(self._client, self._config, self._serialize, self._deserialize)
self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize)
self.managed_rule_sets = ManagedRuleSetsOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self):
# type: () -> None
self._client.close()
def __enter__(self):
# type: () -> CdnManagementClient
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
| 0.810929 | 0.108708 |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
from ._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class CdnManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for CdnManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None:
super(CdnManagementClientConfiguration, self).__init__(**kwargs)
api_version = kwargs.pop("api_version", "2021-06-01") # type: str
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-cdn/{}".format(VERSION))
self._configure(**kwargs)
def _configure(
self, **kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = ARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/_configuration.py
|
_configuration.py
|
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
from ._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class CdnManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for CdnManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None:
super(CdnManagementClientConfiguration, self).__init__(**kwargs)
api_version = kwargs.pop("api_version", "2021-06-01") # type: str
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-cdn/{}".format(VERSION))
self._configure(**kwargs)
def _configure(
self, **kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = ARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
| 0.817866 | 0.078466 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDOriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.AFDOriginGroup"]:
"""Lists all of the existing origin groups within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOriginGroup or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> _models.AFDOriginGroup:
"""Gets an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "AFDOriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: _models.AFDOriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "AFDOriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: _models.AFDOriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters or
IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor origin group under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_afd_origin_groups_operations.py
|
_afd_origin_groups_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDOriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.AFDOriginGroup"]:
"""Lists all of the existing origin groups within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOriginGroup or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> _models.AFDOriginGroup:
"""Gets an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "AFDOriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: _models.AFDOriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "AFDOriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: _models.AFDOriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters or
IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor origin group under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages"} # type: ignore
| 0.817028 | 0.087175 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_or_update_request(
resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class PoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.CdnWebApplicationFirewallPolicy"]:
"""Lists all of the protection policies within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CdnWebApplicationFirewallPolicy or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicyList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicyList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, policy_name: str, **kwargs: Any) -> _models.CdnWebApplicationFirewallPolicy:
"""Retrieve protection policy with specified name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CdnWebApplicationFirewallPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
def _create_or_update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy, (IO, bytes)):
_content = cdn_web_application_firewall_policy
else:
_json = self._serialize.body(cdn_web_application_firewall_policy, "CdnWebApplicationFirewallPolicy")
request = build_create_or_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_or_update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: _models.CdnWebApplicationFirewallPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Is either a model type or a
IO type. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy=cdn_web_application_firewall_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy_patch_parameters, (IO, bytes)):
_content = cdn_web_application_firewall_policy_patch_parameters
else:
_json = self._serialize.body(
cdn_web_application_firewall_policy_patch_parameters, "CdnWebApplicationFirewallPolicyPatchParameters"
)
request = build_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: _models.CdnWebApplicationFirewallPolicyPatchParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Is either a model type or a IO type. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy_patch_parameters=cdn_web_application_firewall_policy_patch_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@distributed_trace
def delete( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, policy_name: str, **kwargs: Any
) -> None:
"""Deletes Policy.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None or the result of cls(response)
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.delete.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_policies_operations.py
|
_policies_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_or_update_request(
resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name",
resource_group_name,
"str",
max_length=80,
min_length=1,
pattern=r"^[a-zA-Z0-9_\-\(\)\.]*[^\.]$",
),
"policyName": _SERIALIZER.url("policy_name", policy_name, "str", max_length=128),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class PoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.CdnWebApplicationFirewallPolicy"]:
"""Lists all of the protection policies within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CdnWebApplicationFirewallPolicy or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicyList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicyList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, policy_name: str, **kwargs: Any) -> _models.CdnWebApplicationFirewallPolicy:
"""Retrieve protection policy with specified name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CdnWebApplicationFirewallPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
def _create_or_update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy, (IO, bytes)):
_content = cdn_web_application_firewall_policy
else:
_json = self._serialize.body(cdn_web_application_firewall_policy, "CdnWebApplicationFirewallPolicy")
request = build_create_or_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_or_update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: _models.CdnWebApplicationFirewallPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Is either a model type or a
IO type. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy=cdn_web_application_firewall_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy_patch_parameters, (IO, bytes)):
_content = cdn_web_application_firewall_policy_patch_parameters
else:
_json = self._serialize.body(
cdn_web_application_firewall_policy_patch_parameters, "CdnWebApplicationFirewallPolicyPatchParameters"
)
request = build_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: _models.CdnWebApplicationFirewallPolicyPatchParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> LROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Is either a model type or a IO type. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CdnWebApplicationFirewallPolicy or the
result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy_patch_parameters=cdn_web_application_firewall_policy_patch_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@distributed_trace
def delete( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, policy_name: str, **kwargs: Any
) -> None:
"""Deletes Policy.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None or the result of cls(response)
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.delete.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
| 0.771843 | 0.070208 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_start_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_stop_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_purge_content_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_load_content_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_custom_domain_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/validateCustomDomain",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/checkResourceUsage",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class EndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.Endpoint"]:
"""Lists existing CDN endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Endpoint or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("EndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any) -> _models.Endpoint:
"""Gets an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Endpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Endpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "Endpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.Endpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "EndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.EndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _start_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_start_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._start_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
@distributed_trace
def begin_start(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Starts an existing CDN endpoint that is on a stopped state.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._start_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
def _stop_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_stop_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._stop_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
@distributed_trace
def begin_stop(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Stops an existing running CDN endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._stop_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "PurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.PurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Is either a model type or a
IO type. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
def _load_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "LoadParameters")
request = build_load_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._load_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_load_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.LoadParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> LROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Is either a model type or a IO type.
Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._load_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_load_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/validateCustomDomain"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.ResourceUsage"]:
"""Checks the quota and usage of geo filters and custom domains under the given endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/checkResourceUsage"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_endpoints_operations.py
|
_endpoints_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_start_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_stop_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_purge_content_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_load_content_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_custom_domain_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/validateCustomDomain",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/checkResourceUsage",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class EndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.Endpoint"]:
"""Lists existing CDN endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Endpoint or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("EndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any) -> _models.Endpoint:
"""Gets an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Endpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Endpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "Endpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.Endpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "EndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.EndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
def _start_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_start_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._start_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
@distributed_trace
def begin_start(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Starts an existing CDN endpoint that is on a stopped state.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._start_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
def _stop_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_stop_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._stop_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
@distributed_trace
def begin_stop(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[_models.Endpoint]:
"""Stops an existing running CDN endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Endpoint or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._stop_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "PurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.PurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Is either a model type or a
IO type. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
def _load_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "LoadParameters")
request = build_load_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._load_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_load_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.LoadParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> LROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Is either a model type or a IO type.
Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._load_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_load_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/validateCustomDomain"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.ResourceUsage"]:
"""Checks the quota and usage of geo filters and custom domains under the given endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/checkResourceUsage"} # type: ignore
| 0.809351 | 0.077938 |
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.Cdn/edgenodes")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class EdgeNodesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`edge_nodes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.EdgeNode"]:
"""Edgenodes are the global Point of Presence (POP) locations used to deliver CDN content to end
users.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either EdgeNode or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.EdgeNode]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EdgenodeResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("EdgenodeResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/edgenodes"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_edge_nodes_operations.py
|
_edge_nodes_operations.py
|
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.Cdn/edgenodes")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class EdgeNodesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`edge_nodes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.EdgeNode"]:
"""Edgenodes are the global Point of Presence (POP) locations used to deliver CDN content to end
users.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either EdgeNode or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.EdgeNode]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EdgenodeResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("EdgenodeResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/edgenodes"} # type: ignore
| 0.851552 | 0.085137 |
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class ResourceUsageOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`resource_usage` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.ResourceUsage"]:
"""Check the quota and actual usage of the CDN profiles under the given subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_resource_usage_operations.py
|
_resource_usage_operations.py
|
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class ResourceUsageOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`resource_usage` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.ResourceUsage"]:
"""Check the quota and actual usage of the CDN profiles under the given subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage"} # type: ignore
| 0.831861 | 0.079603 |
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_secret_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class ValidateOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`validate` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@overload
def secret(
self,
validate_secret_input: _models.ValidateSecretInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def secret(
self, validate_secret_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def secret(
self, validate_secret_input: Union[_models.ValidateSecretInput, IO], **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Is either a model type or a IO type. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSecretOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_secret_input, (IO, bytes)):
_content = validate_secret_input
else:
_json = self._serialize.body(validate_secret_input, "ValidateSecretInput")
request = build_secret_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.secret.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateSecretOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
secret.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_validate_operations.py
|
_validate_operations.py
|
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_secret_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class ValidateOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`validate` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@overload
def secret(
self,
validate_secret_input: _models.ValidateSecretInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def secret(
self, validate_secret_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def secret(
self, validate_secret_input: Union[_models.ValidateSecretInput, IO], **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Is either a model type or a IO type. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSecretOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_secret_input, (IO, bytes)):
_content = validate_secret_input
else:
_json = self._serialize.body(validate_secret_input, "ValidateSecretInput")
request = build_secret_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.secret.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateSecretOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
secret.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret"} # type: ignore
| 0.889379 | 0.079997 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, secret_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"secretName": _SERIALIZER.url("secret_name", secret_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, secret_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"secretName": _SERIALIZER.url("secret_name", secret_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, secret_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"secretName": _SERIALIZER.url("secret_name", secret_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class SecretsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`secrets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> Iterable["_models.Secret"]:
"""Lists existing AzureFrontDoor secrets.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Secret or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecretListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SecretListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any) -> _models.Secret:
"""Gets an existing Secret within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Secret or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Secret
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> _models.Secret:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(secret, (IO, bytes)):
_content = secret
else:
_json = self._serialize.body(secret, "Secret")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: _models.Secret,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: ~azure.mgmt.cdn.models.Secret
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Secret or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Secret or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> LROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Is either a model type or a IO type. Required.
:type secret: ~azure.mgmt.cdn.models.Secret or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Secret or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
secret=secret,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing Secret within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_secrets_operations.py
|
_secrets_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, secret_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"secretName": _SERIALIZER.url("secret_name", secret_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, secret_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"secretName": _SERIALIZER.url("secret_name", secret_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, secret_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"secretName": _SERIALIZER.url("secret_name", secret_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class SecretsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`secrets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> Iterable["_models.Secret"]:
"""Lists existing AzureFrontDoor secrets.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Secret or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecretListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SecretListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any) -> _models.Secret:
"""Gets an existing Secret within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Secret or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Secret
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> _models.Secret:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(secret, (IO, bytes)):
_content = secret
else:
_json = self._serialize.body(secret, "Secret")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: _models.Secret,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: ~azure.mgmt.cdn.models.Secret
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Secret or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Secret or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> LROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Is either a model type or a IO type. Required.
:type secret: ~azure.mgmt.cdn.models.Secret or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Secret or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
secret=secret,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing Secret within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
| 0.791297 | 0.073065 |
import datetime
from typing import Any, Callable, Dict, List, Optional, TypeVar, Union
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_log_analytics_metrics_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
metrics: List[Union[str, _models.LogMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.LogMetricsGranularity],
custom_domains: List[str],
protocols: List[str],
group_by: Optional[List[Union[str, _models.LogMetricsGroupBy]]] = None,
continents: Optional[List[str]] = None,
country_or_regions: Optional[List[str]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsMetrics",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
_params["granularity"] = _SERIALIZER.query("granularity", granularity, "str")
if group_by is not None:
_params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by]
if continents is not None:
_params["continents"] = [_SERIALIZER.query("continents", q, "str") if q is not None else "" for q in continents]
if country_or_regions is not None:
_params["countryOrRegions"] = [
_SERIALIZER.query("country_or_regions", q, "str") if q is not None else "" for q in country_or_regions
]
_params["customDomains"] = [
_SERIALIZER.query("custom_domains", q, "str") if q is not None else "" for q in custom_domains
]
_params["protocols"] = [_SERIALIZER.query("protocols", q, "str") if q is not None else "" for q in protocols]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_log_analytics_rankings_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
rankings: List[Union[str, _models.LogRanking]],
metrics: List[Union[str, _models.LogRankingMetric]],
max_ranking: int,
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
custom_domains: Optional[List[str]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsRankings",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["rankings"] = [_SERIALIZER.query("rankings", q, "str") if q is not None else "" for q in rankings]
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["maxRanking"] = _SERIALIZER.query("max_ranking", max_ranking, "int")
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
if custom_domains is not None:
_params["customDomains"] = [
_SERIALIZER.query("custom_domains", q, "str") if q is not None else "" for q in custom_domains
]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_log_analytics_locations_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsLocations",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_log_analytics_resources_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsResources",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_waf_log_analytics_metrics_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.WafGranularity],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
group_by: Optional[List[Union[str, _models.WafRankingGroupBy]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsMetrics",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
_params["granularity"] = _SERIALIZER.query("granularity", granularity, "str")
if actions is not None:
_params["actions"] = [_SERIALIZER.query("actions", q, "str") if q is not None else "" for q in actions]
if group_by is not None:
_params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by]
if rule_types is not None:
_params["ruleTypes"] = [_SERIALIZER.query("rule_types", q, "str") if q is not None else "" for q in rule_types]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_waf_log_analytics_rankings_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
max_ranking: int,
rankings: List[Union[str, _models.WafRankingType]],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsRankings",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
_params["maxRanking"] = _SERIALIZER.query("max_ranking", max_ranking, "int")
_params["rankings"] = [_SERIALIZER.query("rankings", q, "str") if q is not None else "" for q in rankings]
if actions is not None:
_params["actions"] = [_SERIALIZER.query("actions", q, "str") if q is not None else "" for q in actions]
if rule_types is not None:
_params["ruleTypes"] = [_SERIALIZER.query("rule_types", q, "str") if q is not None else "" for q in rule_types]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class LogAnalyticsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`log_analytics` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def get_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.LogMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.LogMetricsGranularity],
custom_domains: List[str],
protocols: List[str],
group_by: Optional[List[Union[str, _models.LogMetricsGroupBy]]] = None,
continents: Optional[List[str]] = None,
country_or_regions: Optional[List[str]] = None,
**kwargs: Any
) -> _models.MetricsResponse:
"""Get log report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.LogMetricsGranularity
:param custom_domains: Required.
:type custom_domains: list[str]
:param protocols: Required.
:type protocols: list[str]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.LogMetricsGroupBy]
:param continents: Default value is None.
:type continents: list[str]
:param country_or_regions: Default value is None.
:type country_or_regions: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.MetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.MetricsResponse]
request = build_get_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
custom_domains=custom_domains,
protocols=protocols,
group_by=group_by,
continents=continents,
country_or_regions=country_or_regions,
api_version=api_version,
template_url=self.get_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("MetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsMetrics"} # type: ignore
@distributed_trace
def get_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
rankings: List[Union[str, _models.LogRanking]],
metrics: List[Union[str, _models.LogRankingMetric]],
max_ranking: int,
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
custom_domains: Optional[List[str]] = None,
**kwargs: Any
) -> _models.RankingsResponse:
"""Get log analytics ranking report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.LogRanking]
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogRankingMetric]
:param max_ranking: Required.
:type max_ranking: int
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param custom_domains: Default value is None.
:type custom_domains: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RankingsResponse]
request = build_get_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
rankings=rankings,
metrics=metrics,
max_ranking=max_ranking,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
custom_domains=custom_domains,
api_version=api_version,
template_url=self.get_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsRankings"} # type: ignore
@distributed_trace
def get_log_analytics_locations(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ContinentsResponse:
"""Get all available location names for AFD log analytics report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ContinentsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ContinentsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ContinentsResponse]
request = build_get_log_analytics_locations_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_locations.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ContinentsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_locations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsLocations"} # type: ignore
@distributed_trace
def get_log_analytics_resources(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ResourcesResponse:
"""Get all endpoints and custom domains available for AFD log report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ResourcesResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ResourcesResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourcesResponse]
request = build_get_log_analytics_resources_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_resources.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ResourcesResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_resources.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsResources"} # type: ignore
@distributed_trace
def get_waf_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.WafGranularity],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
group_by: Optional[List[Union[str, _models.WafRankingGroupBy]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafMetricsResponse:
"""Get Waf related log analytics report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.WafGranularity
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.WafRankingGroupBy]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafMetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafMetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafMetricsResponse]
request = build_get_waf_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
actions=actions,
group_by=group_by,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafMetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsMetrics"} # type: ignore
@distributed_trace
def get_waf_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
max_ranking: int,
rankings: List[Union[str, _models.WafRankingType]],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafRankingsResponse:
"""Get WAF log analytics charts for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param max_ranking: Required.
:type max_ranking: int
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.WafRankingType]
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafRankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafRankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafRankingsResponse]
request = build_get_waf_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
max_ranking=max_ranking,
rankings=rankings,
actions=actions,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafRankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsRankings"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_log_analytics_operations.py
|
_log_analytics_operations.py
|
import datetime
from typing import Any, Callable, Dict, List, Optional, TypeVar, Union
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_log_analytics_metrics_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
metrics: List[Union[str, _models.LogMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.LogMetricsGranularity],
custom_domains: List[str],
protocols: List[str],
group_by: Optional[List[Union[str, _models.LogMetricsGroupBy]]] = None,
continents: Optional[List[str]] = None,
country_or_regions: Optional[List[str]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsMetrics",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
_params["granularity"] = _SERIALIZER.query("granularity", granularity, "str")
if group_by is not None:
_params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by]
if continents is not None:
_params["continents"] = [_SERIALIZER.query("continents", q, "str") if q is not None else "" for q in continents]
if country_or_regions is not None:
_params["countryOrRegions"] = [
_SERIALIZER.query("country_or_regions", q, "str") if q is not None else "" for q in country_or_regions
]
_params["customDomains"] = [
_SERIALIZER.query("custom_domains", q, "str") if q is not None else "" for q in custom_domains
]
_params["protocols"] = [_SERIALIZER.query("protocols", q, "str") if q is not None else "" for q in protocols]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_log_analytics_rankings_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
rankings: List[Union[str, _models.LogRanking]],
metrics: List[Union[str, _models.LogRankingMetric]],
max_ranking: int,
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
custom_domains: Optional[List[str]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsRankings",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["rankings"] = [_SERIALIZER.query("rankings", q, "str") if q is not None else "" for q in rankings]
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["maxRanking"] = _SERIALIZER.query("max_ranking", max_ranking, "int")
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
if custom_domains is not None:
_params["customDomains"] = [
_SERIALIZER.query("custom_domains", q, "str") if q is not None else "" for q in custom_domains
]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_log_analytics_locations_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsLocations",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_log_analytics_resources_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsResources",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_waf_log_analytics_metrics_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.WafGranularity],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
group_by: Optional[List[Union[str, _models.WafRankingGroupBy]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsMetrics",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
_params["granularity"] = _SERIALIZER.query("granularity", granularity, "str")
if actions is not None:
_params["actions"] = [_SERIALIZER.query("actions", q, "str") if q is not None else "" for q in actions]
if group_by is not None:
_params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by]
if rule_types is not None:
_params["ruleTypes"] = [_SERIALIZER.query("rule_types", q, "str") if q is not None else "" for q in rule_types]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_waf_log_analytics_rankings_request(
resource_group_name: str,
profile_name: str,
subscription_id: str,
*,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
max_ranking: int,
rankings: List[Union[str, _models.WafRankingType]],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsRankings",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
_params["metrics"] = [_SERIALIZER.query("metrics", q, "str") if q is not None else "" for q in metrics]
_params["dateTimeBegin"] = _SERIALIZER.query("date_time_begin", date_time_begin, "iso-8601")
_params["dateTimeEnd"] = _SERIALIZER.query("date_time_end", date_time_end, "iso-8601")
_params["maxRanking"] = _SERIALIZER.query("max_ranking", max_ranking, "int")
_params["rankings"] = [_SERIALIZER.query("rankings", q, "str") if q is not None else "" for q in rankings]
if actions is not None:
_params["actions"] = [_SERIALIZER.query("actions", q, "str") if q is not None else "" for q in actions]
if rule_types is not None:
_params["ruleTypes"] = [_SERIALIZER.query("rule_types", q, "str") if q is not None else "" for q in rule_types]
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class LogAnalyticsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`log_analytics` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def get_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.LogMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.LogMetricsGranularity],
custom_domains: List[str],
protocols: List[str],
group_by: Optional[List[Union[str, _models.LogMetricsGroupBy]]] = None,
continents: Optional[List[str]] = None,
country_or_regions: Optional[List[str]] = None,
**kwargs: Any
) -> _models.MetricsResponse:
"""Get log report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.LogMetricsGranularity
:param custom_domains: Required.
:type custom_domains: list[str]
:param protocols: Required.
:type protocols: list[str]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.LogMetricsGroupBy]
:param continents: Default value is None.
:type continents: list[str]
:param country_or_regions: Default value is None.
:type country_or_regions: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.MetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.MetricsResponse]
request = build_get_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
custom_domains=custom_domains,
protocols=protocols,
group_by=group_by,
continents=continents,
country_or_regions=country_or_regions,
api_version=api_version,
template_url=self.get_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("MetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsMetrics"} # type: ignore
@distributed_trace
def get_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
rankings: List[Union[str, _models.LogRanking]],
metrics: List[Union[str, _models.LogRankingMetric]],
max_ranking: int,
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
custom_domains: Optional[List[str]] = None,
**kwargs: Any
) -> _models.RankingsResponse:
"""Get log analytics ranking report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.LogRanking]
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogRankingMetric]
:param max_ranking: Required.
:type max_ranking: int
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param custom_domains: Default value is None.
:type custom_domains: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RankingsResponse]
request = build_get_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
rankings=rankings,
metrics=metrics,
max_ranking=max_ranking,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
custom_domains=custom_domains,
api_version=api_version,
template_url=self.get_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsRankings"} # type: ignore
@distributed_trace
def get_log_analytics_locations(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ContinentsResponse:
"""Get all available location names for AFD log analytics report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ContinentsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ContinentsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ContinentsResponse]
request = build_get_log_analytics_locations_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_locations.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ContinentsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_locations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsLocations"} # type: ignore
@distributed_trace
def get_log_analytics_resources(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ResourcesResponse:
"""Get all endpoints and custom domains available for AFD log report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ResourcesResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ResourcesResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourcesResponse]
request = build_get_log_analytics_resources_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_resources.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ResourcesResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_resources.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsResources"} # type: ignore
@distributed_trace
def get_waf_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.WafGranularity],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
group_by: Optional[List[Union[str, _models.WafRankingGroupBy]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafMetricsResponse:
"""Get Waf related log analytics report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.WafGranularity
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.WafRankingGroupBy]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafMetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafMetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafMetricsResponse]
request = build_get_waf_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
actions=actions,
group_by=group_by,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafMetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsMetrics"} # type: ignore
@distributed_trace
def get_waf_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
max_ranking: int,
rankings: List[Union[str, _models.WafRankingType]],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafRankingsResponse:
"""Get WAF log analytics charts for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param max_ranking: Required.
:type max_ranking: int
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.WafRankingType]
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafRankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafRankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafRankingsResponse]
request = build_get_waf_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
max_ranking=max_ranking,
rankings=rankings,
actions=actions,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafRankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsRankings"} # type: ignore
| 0.794146 | 0.079353 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_refresh_validation_token_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDCustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.AFDDomain"]:
"""Lists existing AzureFrontDoor domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
or CDN profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDDomain or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.AFDDomain:
"""Gets an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain, (IO, bytes)):
_content = custom_domain
else:
_json = self._serialize.body(custom_domain, "AFDDomain")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: _models.AFDDomain,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Is either a model type or a IO type. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain=custom_domain,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_update_properties, (IO, bytes)):
_content = custom_domain_update_properties
else:
_json = self._serialize.body(custom_domain_update_properties, "AFDDomainUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: _models.AFDDomainUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Is either a model type or a IO type.
Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain_update_properties=custom_domain_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _refresh_validation_token_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_refresh_validation_token_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._refresh_validation_token_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_refresh_validation_token_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
@distributed_trace
def begin_refresh_validation_token(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Updates the domain validation token.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._refresh_validation_token_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_refresh_validation_token.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_afd_custom_domains_operations.py
|
_afd_custom_domains_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_refresh_validation_token_request(
resource_group_name: str, profile_name: str, custom_domain_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDCustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.AFDDomain"]:
"""Lists existing AzureFrontDoor domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
or CDN profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDDomain or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.AFDDomain:
"""Gets an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain, (IO, bytes)):
_content = custom_domain
else:
_json = self._serialize.body(custom_domain, "AFDDomain")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: _models.AFDDomain,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Is either a model type or a IO type. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain=custom_domain,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_update_properties, (IO, bytes)):
_content = custom_domain_update_properties
else:
_json = self._serialize.body(custom_domain_update_properties, "AFDDomainUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: _models.AFDDomainUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Is either a model type or a IO type.
Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDDomain or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain_update_properties=custom_domain_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
def _refresh_validation_token_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_refresh_validation_token_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._refresh_validation_token_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_refresh_validation_token_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
@distributed_trace
def begin_refresh_validation_token(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Updates the domain validation token.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._refresh_validation_token_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_refresh_validation_token.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
| 0.806205 | 0.070368 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class OriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.Origin"]:
"""Lists all of the existing origins within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Origin or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> _models.Origin:
"""Gets an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Origin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Origin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "Origin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: _models.Origin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.Origin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.Origin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "OriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: _models.OriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_origins_operations.py
|
_origins_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class OriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.Origin"]:
"""Lists all of the existing origins within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Origin or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> _models.Origin:
"""Gets an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Origin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Origin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "Origin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: _models.Origin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.Origin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.Origin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "OriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: _models.OriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Origin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
| 0.789883 | 0.071689 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class RoutesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`routes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.Route"]:
"""Lists all of the existing origins within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Route or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("RouteListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> _models.Route:
"""Gets an existing route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Route or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Route
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route, (IO, bytes)):
_content = route
else:
_json = self._serialize.body(route, "Route")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: _models.Route,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: ~azure.mgmt.cdn.models.Route
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Is either a model type or a IO type. Required.
:type route: ~azure.mgmt.cdn.models.Route or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route=route,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route_update_properties, (IO, bytes)):
_content = route_update_properties
else:
_json = self._serialize.body(route_update_properties, "RouteUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: _models.RouteUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Is either a model type or a IO type.
Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route_update_properties=route_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_routes_operations.py
|
_routes_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"routeName": _SERIALIZER.url("route_name", route_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class RoutesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`routes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.Route"]:
"""Lists all of the existing origins within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Route or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("RouteListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> _models.Route:
"""Gets an existing route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Route or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Route
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route, (IO, bytes)):
_content = route
else:
_json = self._serialize.body(route, "Route")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: _models.Route,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: ~azure.mgmt.cdn.models.Route
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Is either a model type or a IO type. Required.
:type route: ~azure.mgmt.cdn.models.Route or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route=route,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route_update_properties, (IO, bytes)):
_content = route_update_properties
else:
_json = self._serialize.body(route_update_properties, "RouteUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: _models.RouteUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Is either a model type or a IO type.
Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route_update_properties=route_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
| 0.797517 | 0.088112 |
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/cdnWebApplicationFirewallManagedRuleSets",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class ManagedRuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`managed_rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.ManagedRuleSetDefinition"]:
"""Lists all available managed rule sets.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ManagedRuleSetDefinition or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ManagedRuleSetDefinition]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagedRuleSetDefinitionList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedRuleSetDefinitionList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/cdnWebApplicationFirewallManagedRuleSets"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_managed_rule_sets_operations.py
|
_managed_rule_sets_operations.py
|
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/cdnWebApplicationFirewallManagedRuleSets",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class ManagedRuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`managed_rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.ManagedRuleSetDefinition"]:
"""Lists all available managed rule sets.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ManagedRuleSetDefinition or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ManagedRuleSetDefinition]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagedRuleSetDefinitionList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedRuleSetDefinitionList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/cdnWebApplicationFirewallManagedRuleSets"} # type: ignore
| 0.835551 | 0.076236 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_purge_content_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_custom_domain_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/validateCustomDomain",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDEndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.AFDEndpoint"]:
"""Lists existing AzureFrontDoor endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDEndpoint or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDEndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.AFDEndpoint:
"""Gets an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDEndpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDEndpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "AFDEndpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.AFDEndpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "AFDEndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.AFDEndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(contents, (IO, bytes)):
_content = contents
else:
_json = self._serialize.body(contents, "AfdPurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: _models.AfdPurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory. Is
either a model type or a IO type. Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
contents=contents,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor endpoint under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/usages"} # type: ignore
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/validateCustomDomain"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_afd_endpoints_operations.py
|
_afd_endpoints_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_purge_content_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_custom_domain_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/validateCustomDomain",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDEndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.AFDEndpoint"]:
"""Lists existing AzureFrontDoor endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDEndpoint or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDEndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.AFDEndpoint:
"""Gets an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDEndpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDEndpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "AFDEndpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.AFDEndpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "AFDEndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.AFDEndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(contents, (IO, bytes)):
_content = contents
else:
_json = self._serialize.body(contents, "AfdPurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: _models.AfdPurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> LROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory. Is
either a model type or a IO type. Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
contents=contents,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor endpoint under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/usages"} # type: ignore
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/validateCustomDomain"} # type: ignore
| 0.808974 | 0.070528 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_rule_set_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class RulesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`rules` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_rule_set(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> Iterable["_models.Rule"]:
"""Lists all of the existing delivery rules within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Rule or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_rule_set_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_rule_set.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("RuleListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> _models.Rule:
"""Gets an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Rule or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Rule
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule, (IO, bytes)):
_content = rule
else:
_json = self._serialize.body(rule, "Rule")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: _models.Rule,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: ~azure.mgmt.cdn.models.Rule
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Is either a model type or a IO type. Required.
:type rule: ~azure.mgmt.cdn.models.Rule or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule=rule,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule_update_properties, (IO, bytes)):
_content = rule_update_properties
else:
_json = self._serialize.body(rule_update_properties, "RuleUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: _models.RuleUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Is either a model type or a IO type.
Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule_update_properties=rule_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_rules_operations.py
|
_rules_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_rule_set_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"ruleName": _SERIALIZER.url("rule_name", rule_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class RulesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`rules` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_rule_set(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> Iterable["_models.Rule"]:
"""Lists all of the existing delivery rules within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Rule or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_rule_set_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_rule_set.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("RuleListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> _models.Rule:
"""Gets an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Rule or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Rule
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule, (IO, bytes)):
_content = rule
else:
_json = self._serialize.body(rule, "Rule")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: _models.Rule,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: ~azure.mgmt.cdn.models.Rule
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Is either a model type or a IO type. Required.
:type rule: ~azure.mgmt.cdn.models.Rule or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule=rule,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule_update_properties, (IO, bytes)):
_content = rule_update_properties
else:
_json = self._serialize.body(rule_update_properties, "RuleUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: _models.RuleUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Is either a model type or a IO type.
Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule_update_properties=rule_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
| 0.801975 | 0.080141 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_check_host_name_availability_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkHostNameAvailability",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of AzureFrontDoor endpoints under the given CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/usages"} # type: ignore
@overload
def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: _models.CheckHostNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: Union[_models.CheckHostNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Is either a model
type or a IO type. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_host_name_availability_input, (IO, bytes)):
_content = check_host_name_availability_input
else:
_json = self._serialize.body(check_host_name_availability_input, "CheckHostNameAvailabilityInput")
request = build_check_host_name_availability_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_host_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_host_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkHostNameAvailability"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_afd_profiles_operations.py
|
_afd_profiles_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_check_host_name_availability_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkHostNameAvailability",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class AFDProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of AzureFrontDoor endpoints under the given CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/usages"} # type: ignore
@overload
def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: _models.CheckHostNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: Union[_models.CheckHostNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Is either a model
type or a IO type. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_host_name_availability_input, (IO, bytes)):
_content = check_host_name_availability_input
else:
_json = self._serialize.body(check_host_name_availability_input, "CheckHostNameAvailabilityInput")
request = build_check_host_name_availability_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_host_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_host_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkHostNameAvailability"} # type: ignore
| 0.841011 | 0.067179 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_disable_custom_https_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_enable_custom_https_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class CustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.CustomDomain"]:
"""Lists all of the existing custom domains within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CustomDomain or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("CustomDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
"""Gets an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CustomDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CustomDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "CustomDomainParameters")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: _models.CustomDomainParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Is either a
model type or a IO type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_properties=custom_domain_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
def _delete_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> Optional[_models.CustomDomain]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CustomDomain]]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
def _disable_custom_https_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_disable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._disable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_disable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
@distributed_trace
def begin_disable_custom_https(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Disable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._disable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_disable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
def _enable_custom_https_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_https_parameters, (IO, bytes)):
_content = custom_domain_https_parameters
else:
if custom_domain_https_parameters is not None:
_json = self._serialize.body(custom_domain_https_parameters, "CustomDomainHttpsParameters")
else:
_json = None
request = build_enable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._enable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_enable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
@overload
def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[_models.CustomDomainHttpsParameters] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[IO] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Is either a model type or a IO type.
Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._enable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_https_parameters=custom_domain_https_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_enable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_custom_domains_operations.py
|
_custom_domains_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_disable_custom_https_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_enable_custom_https_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"customDomainName": _SERIALIZER.url("custom_domain_name", custom_domain_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class CustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.CustomDomain"]:
"""Lists all of the existing custom domains within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CustomDomain or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("CustomDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
"""Gets an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CustomDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CustomDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "CustomDomainParameters")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: _models.CustomDomainParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Is either a
model type or a IO type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_properties=custom_domain_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
def _delete_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> Optional[_models.CustomDomain]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CustomDomain]]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
def _disable_custom_https_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_disable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._disable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_disable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
@distributed_trace
def begin_disable_custom_https(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Disable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._disable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_disable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
def _enable_custom_https_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_https_parameters, (IO, bytes)):
_content = custom_domain_https_parameters
else:
if custom_domain_https_parameters is not None:
_json = self._serialize.body(custom_domain_https_parameters, "CustomDomainHttpsParameters")
else:
_json = None
request = build_enable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._enable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_enable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
@overload
def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[_models.CustomDomainHttpsParameters] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[IO] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> LROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Is either a model type or a IO type.
Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._enable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_https_parameters=custom_domain_https_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_enable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
| 0.786254 | 0.0771 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class OriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.OriginGroup"]:
"""Lists all of the existing origin groups within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OriginGroup or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> _models.OriginGroup:
"""Gets an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: OriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.OriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "OriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: _models.OriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "OriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: _models.OriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_origin_groups_operations.py
|
_origin_groups_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_endpoint_request(
resource_group_name: str, profile_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class OriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> Iterable["_models.OriginGroup"]:
"""Lists all of the existing origin groups within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OriginGroup or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> _models.OriginGroup:
"""Gets an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: OriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.OriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "OriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: _models.OriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "OriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: _models.OriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
| 0.821689 | 0.080285 |
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_check_endpoint_name_availability_request(
resource_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/checkEndpointNameAvailability",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_check_name_availability_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.Cdn/checkNameAvailability")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_check_name_availability_with_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkNameAvailability")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_probe_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class CdnManagementClientOperationsMixin(MixinABC):
@overload
def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: _models.CheckEndpointNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: Union[_models.CheckEndpointNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Is either a model type or a IO
type. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckEndpointNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_endpoint_name_availability_input, (IO, bytes)):
_content = check_endpoint_name_availability_input
else:
_json = self._serialize.body(check_endpoint_name_availability_input, "CheckEndpointNameAvailabilityInput")
request = build_check_endpoint_name_availability_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_endpoint_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckEndpointNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_endpoint_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/checkEndpointNameAvailability"} # type: ignore
@overload
def check_name_availability(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_name_availability(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_name_availability(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability.metadata = {"url": "/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
def check_name_availability_with_subscription(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_name_availability_with_subscription(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_name_availability_with_subscription(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_with_subscription_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability_with_subscription.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability_with_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
def validate_probe(
self, validate_probe_input: _models.ValidateProbeInput, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_probe(
self, validate_probe_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_probe(
self, validate_probe_input: Union[_models.ValidateProbeInput, IO], **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Is either a model type or a IO type. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProbeOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_probe_input, (IO, bytes)):
_content = validate_probe_input
else:
_json = self._serialize.body(validate_probe_input, "ValidateProbeInput")
request = build_validate_probe_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_probe.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateProbeOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_probe.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_cdn_management_client_operations.py
|
_cdn_management_client_operations.py
|
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_check_endpoint_name_availability_request(
resource_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/checkEndpointNameAvailability",
) # pylint: disable=line-too-long
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_check_name_availability_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.Cdn/checkNameAvailability")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_check_name_availability_with_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkNameAvailability")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_validate_probe_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class CdnManagementClientOperationsMixin(MixinABC):
@overload
def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: _models.CheckEndpointNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: Union[_models.CheckEndpointNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Is either a model type or a IO
type. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckEndpointNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_endpoint_name_availability_input, (IO, bytes)):
_content = check_endpoint_name_availability_input
else:
_json = self._serialize.body(check_endpoint_name_availability_input, "CheckEndpointNameAvailabilityInput")
request = build_check_endpoint_name_availability_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_endpoint_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckEndpointNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_endpoint_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/checkEndpointNameAvailability"} # type: ignore
@overload
def check_name_availability(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_name_availability(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_name_availability(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability.metadata = {"url": "/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
def check_name_availability_with_subscription(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def check_name_availability_with_subscription(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def check_name_availability_with_subscription(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_with_subscription_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability_with_subscription.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability_with_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
def validate_probe(
self, validate_probe_input: _models.ValidateProbeInput, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def validate_probe(
self, validate_probe_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def validate_probe(
self, validate_probe_input: Union[_models.ValidateProbeInput, IO], **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Is either a model type or a IO type. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProbeOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_probe_input, (IO, bytes)):
_content = validate_probe_input
else:
_json = self._serialize.body(validate_probe_input, "ValidateProbeInput")
request = build_validate_probe_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_probe.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateProbeOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_probe.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe"} # type: ignore
| 0.849066 | 0.072735 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_origin_group_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class AFDOriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_origin_group(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> Iterable["_models.AFDOrigin"]:
"""Lists all of the existing origins within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_origin_group_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_origin_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_origin_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> _models.AFDOrigin:
"""Gets an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOrigin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOrigin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "AFDOrigin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: _models.AFDOrigin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "AFDOriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: _models.AFDOriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_afd_origins_operations.py
|
_afd_origins_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_origin_group_request(
resource_group_name: str, profile_name: str, origin_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"originGroupName": _SERIALIZER.url("origin_group_name", origin_group_name, "str"),
"originName": _SERIALIZER.url("origin_name", origin_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class AFDOriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`afd_origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_origin_group(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> Iterable["_models.AFDOrigin"]:
"""Lists all of the existing origins within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_origin_group_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_origin_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_origin_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> _models.AFDOrigin:
"""Gets an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOrigin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOrigin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "AFDOrigin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: _models.AFDOrigin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "AFDOriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: _models.AFDOriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
| 0.82828 | 0.084531 |
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.Cdn/operations")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.Operation"]:
"""Lists all of the available CDN REST API operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationsListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OperationsListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/operations"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_operations.py
|
_operations.py
|
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/providers/Microsoft.Cdn/operations")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.Operation"]:
"""Lists all of the available CDN REST API operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationsListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("OperationsListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/operations"} # type: ignore
| 0.854854 | 0.079531 |
from ._cdn_management_client_operations import CdnManagementClientOperationsMixin
from ._afd_profiles_operations import AFDProfilesOperations
from ._afd_custom_domains_operations import AFDCustomDomainsOperations
from ._afd_endpoints_operations import AFDEndpointsOperations
from ._afd_origin_groups_operations import AFDOriginGroupsOperations
from ._afd_origins_operations import AFDOriginsOperations
from ._routes_operations import RoutesOperations
from ._rule_sets_operations import RuleSetsOperations
from ._rules_operations import RulesOperations
from ._security_policies_operations import SecurityPoliciesOperations
from ._secrets_operations import SecretsOperations
from ._validate_operations import ValidateOperations
from ._log_analytics_operations import LogAnalyticsOperations
from ._profiles_operations import ProfilesOperations
from ._endpoints_operations import EndpointsOperations
from ._origins_operations import OriginsOperations
from ._origin_groups_operations import OriginGroupsOperations
from ._custom_domains_operations import CustomDomainsOperations
from ._resource_usage_operations import ResourceUsageOperations
from ._operations import Operations
from ._edge_nodes_operations import EdgeNodesOperations
from ._policies_operations import PoliciesOperations
from ._managed_rule_sets_operations import ManagedRuleSetsOperations
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"CdnManagementClientOperationsMixin",
"AFDProfilesOperations",
"AFDCustomDomainsOperations",
"AFDEndpointsOperations",
"AFDOriginGroupsOperations",
"AFDOriginsOperations",
"RoutesOperations",
"RuleSetsOperations",
"RulesOperations",
"SecurityPoliciesOperations",
"SecretsOperations",
"ValidateOperations",
"LogAnalyticsOperations",
"ProfilesOperations",
"EndpointsOperations",
"OriginsOperations",
"OriginGroupsOperations",
"CustomDomainsOperations",
"ResourceUsageOperations",
"Operations",
"EdgeNodesOperations",
"PoliciesOperations",
"ManagedRuleSetsOperations",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/__init__.py
|
__init__.py
|
from ._cdn_management_client_operations import CdnManagementClientOperationsMixin
from ._afd_profiles_operations import AFDProfilesOperations
from ._afd_custom_domains_operations import AFDCustomDomainsOperations
from ._afd_endpoints_operations import AFDEndpointsOperations
from ._afd_origin_groups_operations import AFDOriginGroupsOperations
from ._afd_origins_operations import AFDOriginsOperations
from ._routes_operations import RoutesOperations
from ._rule_sets_operations import RuleSetsOperations
from ._rules_operations import RulesOperations
from ._security_policies_operations import SecurityPoliciesOperations
from ._secrets_operations import SecretsOperations
from ._validate_operations import ValidateOperations
from ._log_analytics_operations import LogAnalyticsOperations
from ._profiles_operations import ProfilesOperations
from ._endpoints_operations import EndpointsOperations
from ._origins_operations import OriginsOperations
from ._origin_groups_operations import OriginGroupsOperations
from ._custom_domains_operations import CustomDomainsOperations
from ._resource_usage_operations import ResourceUsageOperations
from ._operations import Operations
from ._edge_nodes_operations import EdgeNodesOperations
from ._policies_operations import PoliciesOperations
from ._managed_rule_sets_operations import ManagedRuleSetsOperations
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"CdnManagementClientOperationsMixin",
"AFDProfilesOperations",
"AFDCustomDomainsOperations",
"AFDEndpointsOperations",
"AFDOriginGroupsOperations",
"AFDOriginsOperations",
"RoutesOperations",
"RuleSetsOperations",
"RulesOperations",
"SecurityPoliciesOperations",
"SecretsOperations",
"ValidateOperations",
"LogAnalyticsOperations",
"ProfilesOperations",
"EndpointsOperations",
"OriginsOperations",
"OriginGroupsOperations",
"CustomDomainsOperations",
"ResourceUsageOperations",
"Operations",
"EdgeNodesOperations",
"PoliciesOperations",
"ManagedRuleSetsOperations",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
| 0.40157 | 0.054727 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/profiles")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_generate_sso_uri_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/generateSsoUri",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_supported_optimization_types_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getSupportedOptimizationTypes",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkResourceUsage",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class ProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within
an Azure subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace
def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within a
resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_resource_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.Profile:
"""Gets an Azure Front Door Standard or Azure Front Door Premium or CDN profile with the specified
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Profile or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Profile
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
def _create_initial(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile, (IO, bytes)):
_content = profile
else:
_json = self._serialize.body(profile, "Profile")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: _models.Profile,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: ~azure.mgmt.cdn.models.Profile
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> LROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Is either a model type or a
IO type. Required.
:type profile: ~azure.mgmt.cdn.models.Profile or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile=profile,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile_update_parameters, (IO, bytes)):
_content = profile_update_parameters
else:
_json = self._serialize.body(profile_update_parameters, "ProfileUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: _models.ProfileUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile. Is
either a model type or a IO type. Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile_update_parameters=profile_update_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace
def begin_delete(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> LROPoller[None]:
"""Deletes an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified parameters. Deleting a profile will result in the deletion of all of the
sub-resources including endpoints, origins and custom domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace
def generate_sso_uri(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.SsoUri:
"""Generates a dynamic SSO URI used to sign in to the CDN supplemental portal. Supplemental portal
is used to configure advanced feature capabilities that are not yet available in the Azure
portal, such as core reports in a standard profile; rules engine, advanced HTTP reports, and
real-time stats and alerts in a premium profile. The SSO URI changes approximately every 10
minutes.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SsoUri or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SsoUri
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SsoUri]
request = build_generate_sso_uri_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.generate_sso_uri.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SsoUri", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
generate_sso_uri.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/generateSsoUri"} # type: ignore
@distributed_trace
def list_supported_optimization_types(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.SupportedOptimizationTypesListResult:
"""Gets the supported optimization types for the current profile. A user can create an endpoint
with an optimization type from the listed values.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SupportedOptimizationTypesListResult or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SupportedOptimizationTypesListResult
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedOptimizationTypesListResult]
request = build_list_supported_optimization_types_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_supported_optimization_types.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SupportedOptimizationTypesListResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_supported_optimization_types.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getSupportedOptimizationTypes"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.ResourceUsage"]:
"""Checks the quota and actual usage of endpoints under the given Azure Front Door Standard or
Azure Front Door Premium or CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkResourceUsage"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_profiles_operations.py
|
_profiles_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/profiles")
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_update_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_generate_sso_uri_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/generateSsoUri",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_supported_optimization_types_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getSupportedOptimizationTypes",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkResourceUsage",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class ProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> Iterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within
an Azure subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace
def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within a
resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_resource_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.Profile:
"""Gets an Azure Front Door Standard or Azure Front Door Premium or CDN profile with the specified
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Profile or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Profile
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
def _create_initial(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile, (IO, bytes)):
_content = profile
else:
_json = self._serialize.body(profile, "Profile")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: _models.Profile,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: ~azure.mgmt.cdn.models.Profile
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> LROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Is either a model type or a
IO type. Required.
:type profile: ~azure.mgmt.cdn.models.Profile or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile=profile,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
def _update_initial(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile_update_parameters, (IO, bytes)):
_content = profile_update_parameters
else:
_json = self._serialize.body(profile_update_parameters, "ProfileUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: _models.ProfileUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile. Is
either a model type or a IO type. Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either Profile or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile_update_parameters=profile_update_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace
def begin_delete(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> LROPoller[None]:
"""Deletes an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified parameters. Deleting a profile will result in the deletion of all of the
sub-resources including endpoints, origins and custom domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace
def generate_sso_uri(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.SsoUri:
"""Generates a dynamic SSO URI used to sign in to the CDN supplemental portal. Supplemental portal
is used to configure advanced feature capabilities that are not yet available in the Azure
portal, such as core reports in a standard profile; rules engine, advanced HTTP reports, and
real-time stats and alerts in a premium profile. The SSO URI changes approximately every 10
minutes.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SsoUri or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SsoUri
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SsoUri]
request = build_generate_sso_uri_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.generate_sso_uri.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SsoUri", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
generate_sso_uri.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/generateSsoUri"} # type: ignore
@distributed_trace
def list_supported_optimization_types(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.SupportedOptimizationTypesListResult:
"""Gets the supported optimization types for the current profile. A user can create an endpoint
with an optimization type from the listed values.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SupportedOptimizationTypesListResult or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SupportedOptimizationTypesListResult
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedOptimizationTypesListResult]
request = build_list_supported_optimization_types_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_supported_optimization_types.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SupportedOptimizationTypesListResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_supported_optimization_types.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getSupportedOptimizationTypes"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.ResourceUsage"]:
"""Checks the quota and actual usage of endpoints under the given Azure Front Door Standard or
Azure Front Door Premium or CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkResourceUsage"} # type: ignore
| 0.801237 | 0.082549 |
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class RuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.RuleSet"]:
"""Lists existing AzureFrontDoor rule sets within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either RuleSet or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.RuleSet]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSetListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("RuleSetListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any) -> _models.RuleSet:
"""Gets an existing AzureFrontDoor rule set with the specified rule set name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def create(self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any) -> _models.RuleSet:
"""Creates a new rule set within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.create.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("RuleSet", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing AzureFrontDoor rule set with the specified rule set name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor rule set under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/usages"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_rule_sets_operations.py
|
_rule_sets_operations.py
|
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_list_resource_usage_request(
resource_group_name: str, profile_name: str, rule_set_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/usages",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"ruleSetName": _SERIALIZER.url("rule_set_name", rule_set_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class RuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.RuleSet"]:
"""Lists existing AzureFrontDoor rule sets within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either RuleSet or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.RuleSet]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSetListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("RuleSetListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets"} # type: ignore
@distributed_trace
def get(self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any) -> _models.RuleSet:
"""Gets an existing AzureFrontDoor rule set with the specified rule set name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def create(self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any) -> _models.RuleSet:
"""Creates a new rule set within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.create.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("RuleSet", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing AzureFrontDoor rule set with the specified rule set name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> Iterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor rule set under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/usages"} # type: ignore
| 0.783243 | 0.080033 |
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_patch_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class SecurityPoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`security_policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.SecurityPolicy"]:
"""Lists security policies associated with the profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SecurityPolicy or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicyListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SecurityPolicyListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> _models.SecurityPolicy:
"""Gets an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SecurityPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SecurityPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy, (IO, bytes)):
_content = security_policy
else:
_json = self._serialize.body(security_policy, "SecurityPolicy")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: _models.SecurityPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Is either a model type or a IO type.
Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy=security_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
def _patch_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy_update_properties, (IO, bytes)):
_content = security_policy_update_properties
else:
_json = self._serialize.body(security_policy_update_properties, "SecurityPolicyUpdateParameters")
request = build_patch_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._patch_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_patch_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: _models.SecurityPolicyUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Is either a model
type or a IO type. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._patch_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy_update_properties=security_policy_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_patch.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing security policy within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/operations/_security_policies_operations.py
|
_security_policies_operations.py
|
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from .._serialization import Serializer
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_profile_request(
resource_group_name: str, profile_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_patch_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, profile_name: str, security_policy_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-06-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
),
"profileName": _SERIALIZER.url("profile_name", profile_name, "str"),
"securityPolicyName": _SERIALIZER.url("security_policy_name", security_policy_name, "str"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
class SecurityPoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.CdnManagementClient`'s
:attr:`security_policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> Iterable["_models.SecurityPolicy"]:
"""Lists security policies associated with the profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SecurityPolicy or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicyListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SecurityPolicyListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies"} # type: ignore
@distributed_trace
def get(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> _models.SecurityPolicy:
"""Gets an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SecurityPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SecurityPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
def _create_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy, (IO, bytes)):
_content = security_policy
else:
_json = self._serialize.body(security_policy, "SecurityPolicy")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: _models.SecurityPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Is either a model type or a IO type.
Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy=security_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
def _patch_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy_update_properties, (IO, bytes)):
_content = security_policy_update_properties
else:
_json = self._serialize.body(security_policy_update_properties, "SecurityPolicyUpdateParameters")
request = build_patch_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._patch_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_patch_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: _models.SecurityPolicyUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> LROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Is either a model
type or a IO type. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._patch_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy_update_properties=security_policy_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_patch.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@distributed_trace
def begin_delete(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> LROPoller[None]:
"""Deletes an existing security policy within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
| 0.811415 | 0.074568 |
from copy import deepcopy
from typing import Any, Awaitable, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from .. import models
from .._serialization import Deserializer, Serializer
from ._configuration import CdnManagementClientConfiguration
from .operations import (
AFDCustomDomainsOperations,
AFDEndpointsOperations,
AFDOriginGroupsOperations,
AFDOriginsOperations,
AFDProfilesOperations,
CdnManagementClientOperationsMixin,
CustomDomainsOperations,
EdgeNodesOperations,
EndpointsOperations,
LogAnalyticsOperations,
ManagedRuleSetsOperations,
Operations,
OriginGroupsOperations,
OriginsOperations,
PoliciesOperations,
ProfilesOperations,
ResourceUsageOperations,
RoutesOperations,
RuleSetsOperations,
RulesOperations,
SecretsOperations,
SecurityPoliciesOperations,
ValidateOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class CdnManagementClient(
CdnManagementClientOperationsMixin
): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes
"""Cdn Management Client.
:ivar afd_profiles: AFDProfilesOperations operations
:vartype afd_profiles: azure.mgmt.cdn.aio.operations.AFDProfilesOperations
:ivar afd_custom_domains: AFDCustomDomainsOperations operations
:vartype afd_custom_domains: azure.mgmt.cdn.aio.operations.AFDCustomDomainsOperations
:ivar afd_endpoints: AFDEndpointsOperations operations
:vartype afd_endpoints: azure.mgmt.cdn.aio.operations.AFDEndpointsOperations
:ivar afd_origin_groups: AFDOriginGroupsOperations operations
:vartype afd_origin_groups: azure.mgmt.cdn.aio.operations.AFDOriginGroupsOperations
:ivar afd_origins: AFDOriginsOperations operations
:vartype afd_origins: azure.mgmt.cdn.aio.operations.AFDOriginsOperations
:ivar routes: RoutesOperations operations
:vartype routes: azure.mgmt.cdn.aio.operations.RoutesOperations
:ivar rule_sets: RuleSetsOperations operations
:vartype rule_sets: azure.mgmt.cdn.aio.operations.RuleSetsOperations
:ivar rules: RulesOperations operations
:vartype rules: azure.mgmt.cdn.aio.operations.RulesOperations
:ivar security_policies: SecurityPoliciesOperations operations
:vartype security_policies: azure.mgmt.cdn.aio.operations.SecurityPoliciesOperations
:ivar secrets: SecretsOperations operations
:vartype secrets: azure.mgmt.cdn.aio.operations.SecretsOperations
:ivar validate: ValidateOperations operations
:vartype validate: azure.mgmt.cdn.aio.operations.ValidateOperations
:ivar log_analytics: LogAnalyticsOperations operations
:vartype log_analytics: azure.mgmt.cdn.aio.operations.LogAnalyticsOperations
:ivar profiles: ProfilesOperations operations
:vartype profiles: azure.mgmt.cdn.aio.operations.ProfilesOperations
:ivar endpoints: EndpointsOperations operations
:vartype endpoints: azure.mgmt.cdn.aio.operations.EndpointsOperations
:ivar origins: OriginsOperations operations
:vartype origins: azure.mgmt.cdn.aio.operations.OriginsOperations
:ivar origin_groups: OriginGroupsOperations operations
:vartype origin_groups: azure.mgmt.cdn.aio.operations.OriginGroupsOperations
:ivar custom_domains: CustomDomainsOperations operations
:vartype custom_domains: azure.mgmt.cdn.aio.operations.CustomDomainsOperations
:ivar resource_usage: ResourceUsageOperations operations
:vartype resource_usage: azure.mgmt.cdn.aio.operations.ResourceUsageOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.cdn.aio.operations.Operations
:ivar edge_nodes: EdgeNodesOperations operations
:vartype edge_nodes: azure.mgmt.cdn.aio.operations.EdgeNodesOperations
:ivar policies: PoliciesOperations operations
:vartype policies: azure.mgmt.cdn.aio.operations.PoliciesOperations
:ivar managed_rule_sets: ManagedRuleSetsOperations operations
:vartype managed_rule_sets: azure.mgmt.cdn.aio.operations.ManagedRuleSetsOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = CdnManagementClientConfiguration(
credential=credential, subscription_id=subscription_id, **kwargs
)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.afd_profiles = AFDProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_custom_domains = AFDCustomDomainsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_endpoints = AFDEndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_origin_groups = AFDOriginGroupsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_origins = AFDOriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.routes = RoutesOperations(self._client, self._config, self._serialize, self._deserialize)
self.rule_sets = RuleSetsOperations(self._client, self._config, self._serialize, self._deserialize)
self.rules = RulesOperations(self._client, self._config, self._serialize, self._deserialize)
self.security_policies = SecurityPoliciesOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.secrets = SecretsOperations(self._client, self._config, self._serialize, self._deserialize)
self.validate = ValidateOperations(self._client, self._config, self._serialize, self._deserialize)
self.log_analytics = LogAnalyticsOperations(self._client, self._config, self._serialize, self._deserialize)
self.profiles = ProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.endpoints = EndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origins = OriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origin_groups = OriginGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.custom_domains = CustomDomainsOperations(self._client, self._config, self._serialize, self._deserialize)
self.resource_usage = ResourceUsageOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.edge_nodes = EdgeNodesOperations(self._client, self._config, self._serialize, self._deserialize)
self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize)
self.managed_rule_sets = ManagedRuleSetsOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "CdnManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/_cdn_management_client.py
|
_cdn_management_client.py
|
from copy import deepcopy
from typing import Any, Awaitable, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from .. import models
from .._serialization import Deserializer, Serializer
from ._configuration import CdnManagementClientConfiguration
from .operations import (
AFDCustomDomainsOperations,
AFDEndpointsOperations,
AFDOriginGroupsOperations,
AFDOriginsOperations,
AFDProfilesOperations,
CdnManagementClientOperationsMixin,
CustomDomainsOperations,
EdgeNodesOperations,
EndpointsOperations,
LogAnalyticsOperations,
ManagedRuleSetsOperations,
Operations,
OriginGroupsOperations,
OriginsOperations,
PoliciesOperations,
ProfilesOperations,
ResourceUsageOperations,
RoutesOperations,
RuleSetsOperations,
RulesOperations,
SecretsOperations,
SecurityPoliciesOperations,
ValidateOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class CdnManagementClient(
CdnManagementClientOperationsMixin
): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes
"""Cdn Management Client.
:ivar afd_profiles: AFDProfilesOperations operations
:vartype afd_profiles: azure.mgmt.cdn.aio.operations.AFDProfilesOperations
:ivar afd_custom_domains: AFDCustomDomainsOperations operations
:vartype afd_custom_domains: azure.mgmt.cdn.aio.operations.AFDCustomDomainsOperations
:ivar afd_endpoints: AFDEndpointsOperations operations
:vartype afd_endpoints: azure.mgmt.cdn.aio.operations.AFDEndpointsOperations
:ivar afd_origin_groups: AFDOriginGroupsOperations operations
:vartype afd_origin_groups: azure.mgmt.cdn.aio.operations.AFDOriginGroupsOperations
:ivar afd_origins: AFDOriginsOperations operations
:vartype afd_origins: azure.mgmt.cdn.aio.operations.AFDOriginsOperations
:ivar routes: RoutesOperations operations
:vartype routes: azure.mgmt.cdn.aio.operations.RoutesOperations
:ivar rule_sets: RuleSetsOperations operations
:vartype rule_sets: azure.mgmt.cdn.aio.operations.RuleSetsOperations
:ivar rules: RulesOperations operations
:vartype rules: azure.mgmt.cdn.aio.operations.RulesOperations
:ivar security_policies: SecurityPoliciesOperations operations
:vartype security_policies: azure.mgmt.cdn.aio.operations.SecurityPoliciesOperations
:ivar secrets: SecretsOperations operations
:vartype secrets: azure.mgmt.cdn.aio.operations.SecretsOperations
:ivar validate: ValidateOperations operations
:vartype validate: azure.mgmt.cdn.aio.operations.ValidateOperations
:ivar log_analytics: LogAnalyticsOperations operations
:vartype log_analytics: azure.mgmt.cdn.aio.operations.LogAnalyticsOperations
:ivar profiles: ProfilesOperations operations
:vartype profiles: azure.mgmt.cdn.aio.operations.ProfilesOperations
:ivar endpoints: EndpointsOperations operations
:vartype endpoints: azure.mgmt.cdn.aio.operations.EndpointsOperations
:ivar origins: OriginsOperations operations
:vartype origins: azure.mgmt.cdn.aio.operations.OriginsOperations
:ivar origin_groups: OriginGroupsOperations operations
:vartype origin_groups: azure.mgmt.cdn.aio.operations.OriginGroupsOperations
:ivar custom_domains: CustomDomainsOperations operations
:vartype custom_domains: azure.mgmt.cdn.aio.operations.CustomDomainsOperations
:ivar resource_usage: ResourceUsageOperations operations
:vartype resource_usage: azure.mgmt.cdn.aio.operations.ResourceUsageOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.cdn.aio.operations.Operations
:ivar edge_nodes: EdgeNodesOperations operations
:vartype edge_nodes: azure.mgmt.cdn.aio.operations.EdgeNodesOperations
:ivar policies: PoliciesOperations operations
:vartype policies: azure.mgmt.cdn.aio.operations.PoliciesOperations
:ivar managed_rule_sets: ManagedRuleSetsOperations operations
:vartype managed_rule_sets: azure.mgmt.cdn.aio.operations.ManagedRuleSetsOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = CdnManagementClientConfiguration(
credential=credential, subscription_id=subscription_id, **kwargs
)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.afd_profiles = AFDProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_custom_domains = AFDCustomDomainsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_endpoints = AFDEndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.afd_origin_groups = AFDOriginGroupsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.afd_origins = AFDOriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.routes = RoutesOperations(self._client, self._config, self._serialize, self._deserialize)
self.rule_sets = RuleSetsOperations(self._client, self._config, self._serialize, self._deserialize)
self.rules = RulesOperations(self._client, self._config, self._serialize, self._deserialize)
self.security_policies = SecurityPoliciesOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.secrets = SecretsOperations(self._client, self._config, self._serialize, self._deserialize)
self.validate = ValidateOperations(self._client, self._config, self._serialize, self._deserialize)
self.log_analytics = LogAnalyticsOperations(self._client, self._config, self._serialize, self._deserialize)
self.profiles = ProfilesOperations(self._client, self._config, self._serialize, self._deserialize)
self.endpoints = EndpointsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origins = OriginsOperations(self._client, self._config, self._serialize, self._deserialize)
self.origin_groups = OriginGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.custom_domains = CustomDomainsOperations(self._client, self._config, self._serialize, self._deserialize)
self.resource_usage = ResourceUsageOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.edge_nodes = EdgeNodesOperations(self._client, self._config, self._serialize, self._deserialize)
self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize)
self.managed_rule_sets = ManagedRuleSetsOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "CdnManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
| 0.797162 | 0.089973 |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class CdnManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for CdnManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None:
super(CdnManagementClientConfiguration, self).__init__(**kwargs)
api_version = kwargs.pop("api_version", "2021-06-01") # type: str
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-cdn/{}".format(VERSION))
self._configure(**kwargs)
def _configure(self, **kwargs: Any) -> None:
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/_configuration.py
|
_configuration.py
|
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class CdnManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for CdnManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Azure Subscription ID. Required.
:type subscription_id: str
:keyword api_version: Api Version. Default value is "2021-06-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None:
super(CdnManagementClientConfiguration, self).__init__(**kwargs)
api_version = kwargs.pop("api_version", "2021-06-01") # type: str
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
self.credential = credential
self.subscription_id = subscription_id
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"])
kwargs.setdefault("sdk_moniker", "mgmt-cdn/{}".format(VERSION))
self._configure(**kwargs)
def _configure(self, **kwargs: Any) -> None:
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(
self.credential, *self.credential_scopes, **kwargs
)
| 0.824285 | 0.080321 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_origin_groups_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDOriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDOriginGroup"]:
"""Lists all of the existing origin groups within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOriginGroup or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> _models.AFDOriginGroup:
"""Gets an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "AFDOriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: _models.AFDOriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "AFDOriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: _models.AFDOriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters or
IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor origin group under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_afd_origin_groups_operations.py
|
_afd_origin_groups_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_origin_groups_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDOriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDOriginGroup"]:
"""Lists all of the existing origin groups within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOriginGroup or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> _models.AFDOriginGroup:
"""Gets an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "AFDOriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: _models.AFDOriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group: Union[_models.AFDOriginGroup, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Creates a new origin group within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.AFDOriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "AFDOriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: _models.AFDOriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.AFDOriginGroupUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOriginGroup]:
"""Updates an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.AFDOriginGroupUpdateParameters or
IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin group within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor origin group under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages"} # type: ignore
| 0.894942 | 0.079496 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._policies_operations import (
build_create_or_update_request,
build_delete_request,
build_get_request,
build_list_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class PoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.CdnWebApplicationFirewallPolicy"]:
"""Lists all of the protection policies within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CdnWebApplicationFirewallPolicy or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicyList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicyList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, policy_name: str, **kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
"""Retrieve protection policy with specified name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CdnWebApplicationFirewallPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy, (IO, bytes)):
_content = cdn_web_application_firewall_policy
else:
_json = self._serialize.body(cdn_web_application_firewall_policy, "CdnWebApplicationFirewallPolicy")
request = build_create_or_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_or_update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
async def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: _models.CdnWebApplicationFirewallPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Is either a model type or a
IO type. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy=cdn_web_application_firewall_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy_patch_parameters, (IO, bytes)):
_content = cdn_web_application_firewall_policy_patch_parameters
else:
_json = self._serialize.body(
cdn_web_application_firewall_policy_patch_parameters, "CdnWebApplicationFirewallPolicyPatchParameters"
)
request = build_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: _models.CdnWebApplicationFirewallPolicyPatchParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Is either a model type or a IO type. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy_patch_parameters=cdn_web_application_firewall_policy_patch_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@distributed_trace_async
async def delete( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, policy_name: str, **kwargs: Any
) -> None:
"""Deletes Policy.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None or the result of cls(response)
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.delete.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_policies_operations.py
|
_policies_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._policies_operations import (
build_create_or_update_request,
build_delete_request,
build_get_request,
build_list_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class PoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.CdnWebApplicationFirewallPolicy"]:
"""Lists all of the protection policies within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CdnWebApplicationFirewallPolicy or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicyList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicyList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, policy_name: str, **kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
"""Retrieve protection policy with specified name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CdnWebApplicationFirewallPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy, (IO, bytes)):
_content = cdn_web_application_firewall_policy
else:
_json = self._serialize.body(cdn_web_application_firewall_policy, "CdnWebApplicationFirewallPolicy")
request = build_create_or_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_or_update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
async def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: _models.CdnWebApplicationFirewallPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Required.
:type cdn_web_application_firewall_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create_or_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy: Union[_models.CdnWebApplicationFirewallPolicy, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Create or update policy with specified rule set name within a resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy: Policy to be created. Is either a model type or a
IO type. Required.
:type cdn_web_application_firewall_policy:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy=cdn_web_application_firewall_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> _models.CdnWebApplicationFirewallPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(cdn_web_application_firewall_policy_patch_parameters, (IO, bytes)):
_content = cdn_web_application_firewall_policy_patch_parameters
else:
_json = self._serialize.body(
cdn_web_application_firewall_policy_patch_parameters, "CdnWebApplicationFirewallPolicyPatchParameters"
)
request = build_update_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: _models.CdnWebApplicationFirewallPolicyPatchParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Required.
:type cdn_web_application_firewall_policy_patch_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
policy_name: str,
cdn_web_application_firewall_policy_patch_parameters: Union[
_models.CdnWebApplicationFirewallPolicyPatchParameters, IO
],
**kwargs: Any
) -> AsyncLROPoller[_models.CdnWebApplicationFirewallPolicy]:
"""Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the
specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:param cdn_web_application_firewall_policy_patch_parameters: CdnWebApplicationFirewallPolicy
parameters to be patched. Is either a model type or a IO type. Required.
:type cdn_web_application_firewall_policy_patch_parameters:
~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicyPatchParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CdnWebApplicationFirewallPolicy or
the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CdnWebApplicationFirewallPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnWebApplicationFirewallPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
policy_name=policy_name,
cdn_web_application_firewall_policy_patch_parameters=cdn_web_application_firewall_policy_patch_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CdnWebApplicationFirewallPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
@distributed_trace_async
async def delete( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, policy_name: str, **kwargs: Any
) -> None:
"""Deletes Policy.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param policy_name: The name of the CdnWebApplicationFirewallPolicy. Required.
:type policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None or the result of cls(response)
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
policy_name=policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.delete.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"} # type: ignore
| 0.891569 | 0.076891 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._endpoints_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
build_load_content_request,
build_purge_content_request,
build_start_request,
build_stop_request,
build_update_request,
build_validate_custom_domain_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class EndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.Endpoint"]:
"""Lists existing CDN endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Endpoint or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("EndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
"""Gets an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Endpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Endpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "Endpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.Endpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "EndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.EndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _start_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_start_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._start_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
@distributed_trace_async
async def begin_start(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Starts an existing CDN endpoint that is on a stopped state.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._start_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
async def _stop_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_stop_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._stop_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
@distributed_trace_async
async def begin_stop(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Stops an existing running CDN endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._stop_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
async def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "PurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.PurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Is either a model type or a
IO type. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
async def _load_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "LoadParameters")
request = build_load_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._load_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_load_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
async def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.LoadParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Is either a model type or a IO type.
Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._load_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_load_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/validateCustomDomain"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.ResourceUsage"]:
"""Checks the quota and usage of geo filters and custom domains under the given endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/checkResourceUsage"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_endpoints_operations.py
|
_endpoints_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._endpoints_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
build_load_content_request,
build_purge_content_request,
build_start_request,
build_stop_request,
build_update_request,
build_validate_custom_domain_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class EndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.Endpoint"]:
"""Lists existing CDN endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Endpoint or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("EndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
"""Gets an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Endpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Endpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "Endpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.Endpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.Endpoint, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Creates a new CDN endpoint with the specified endpoint name under the specified subscription,
resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.Endpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "EndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.EndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.EndpointUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Updates an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile. Only tags can be updated after creating an endpoint.
To update origins, use the Update Origin operation. To update origin groups, use the Update
Origin group operation. To update custom domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.EndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing CDN endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}"} # type: ignore
async def _start_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_start_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._start_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
@distributed_trace_async
async def begin_start(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Starts an existing CDN endpoint that is on a stopped state.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._start_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/start"} # type: ignore
async def _stop_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.Endpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
request = build_stop_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._stop_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Endpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
@distributed_trace_async
async def begin_stop(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.Endpoint]:
"""Stops an existing running CDN endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Endpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Endpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Endpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._stop_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Endpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/stop"} # type: ignore
async def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "PurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.PurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.PurgeParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from CDN.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be purged. Path can be a full URL, e.g.
'/pictures/city.png' which removes a single file, or a directory with a wildcard, e.g.
'/pictures/*' which removes all folders and files in the directory. Is either a model type or a
IO type. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.PurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge"} # type: ignore
async def _load_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(content_file_paths, (IO, bytes)):
_content = content_file_paths
else:
_json = self._serialize.body(content_file_paths, "LoadParameters")
request = build_load_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._load_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_load_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
async def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: _models.LoadParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Required.
:type content_file_paths: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_load_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
content_file_paths: Union[_models.LoadParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Pre-loads a content to CDN. Available for Verizon Profiles.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param content_file_paths: The path to the content to be loaded. Path should be a full URL,
e.g. ‘/pictures/city.png' which loads a single file. Is either a model type or a IO type.
Required.
:type content_file_paths: ~azure.mgmt.cdn.models.LoadParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._load_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
content_file_paths=content_file_paths,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_load_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/load"} # type: ignore
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/validateCustomDomain"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.ResourceUsage"]:
"""Checks the quota and usage of geo filters and custom domains under the given endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/checkResourceUsage"} # type: ignore
| 0.889451 | 0.082107 |
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._edge_nodes_operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class EdgeNodesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`edge_nodes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.EdgeNode"]:
"""Edgenodes are the global Point of Presence (POP) locations used to deliver CDN content to end
users.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either EdgeNode or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.EdgeNode]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EdgenodeResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("EdgenodeResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/edgenodes"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_edge_nodes_operations.py
|
_edge_nodes_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._edge_nodes_operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class EdgeNodesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`edge_nodes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.EdgeNode"]:
"""Edgenodes are the global Point of Presence (POP) locations used to deliver CDN content to end
users.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either EdgeNode or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.EdgeNode]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.EdgenodeResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("EdgenodeResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/edgenodes"} # type: ignore
| 0.875561 | 0.09947 |
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._resource_usage_operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ResourceUsageOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`resource_usage` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.ResourceUsage"]:
"""Check the quota and actual usage of the CDN profiles under the given subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_resource_usage_operations.py
|
_resource_usage_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._resource_usage_operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ResourceUsageOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`resource_usage` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.ResourceUsage"]:
"""Check the quota and actual usage of the CDN profiles under the given subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkResourceUsage"} # type: ignore
| 0.873188 | 0.09187 |
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._validate_operations import build_secret_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ValidateOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`validate` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@overload
async def secret(
self,
validate_secret_input: _models.ValidateSecretInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def secret(
self, validate_secret_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def secret(
self, validate_secret_input: Union[_models.ValidateSecretInput, IO], **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Is either a model type or a IO type. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSecretOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_secret_input, (IO, bytes)):
_content = validate_secret_input
else:
_json = self._serialize.body(validate_secret_input, "ValidateSecretInput")
request = build_secret_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.secret.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateSecretOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
secret.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_validate_operations.py
|
_validate_operations.py
|
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._validate_operations import build_secret_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ValidateOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`validate` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@overload
async def secret(
self,
validate_secret_input: _models.ValidateSecretInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def secret(
self, validate_secret_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Required.
:type validate_secret_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def secret(
self, validate_secret_input: Union[_models.ValidateSecretInput, IO], **kwargs: Any
) -> _models.ValidateSecretOutput:
"""Validate a Secret in the profile.
:param validate_secret_input: The Secret source. Is either a model type or a IO type. Required.
:type validate_secret_input: ~azure.mgmt.cdn.models.ValidateSecretInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateSecretOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateSecretOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSecretOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_secret_input, (IO, bytes)):
_content = validate_secret_input
else:
_json = self._serialize.body(validate_secret_input, "ValidateSecretInput")
request = build_secret_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.secret.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateSecretOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
secret.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret"} # type: ignore
| 0.911124 | 0.098252 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._secrets_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SecretsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`secrets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.Secret"]:
"""Lists existing AzureFrontDoor secrets.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Secret or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecretListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SecretListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets"} # type: ignore
@distributed_trace_async
async def get(self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any) -> _models.Secret:
"""Gets an existing Secret within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Secret or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Secret
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> _models.Secret:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(secret, (IO, bytes)):
_content = secret
else:
_json = self._serialize.body(secret, "Secret")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: _models.Secret,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: ~azure.mgmt.cdn.models.Secret
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Secret or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Secret or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Is either a model type or a IO type. Required.
:type secret: ~azure.mgmt.cdn.models.Secret or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Secret or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
secret=secret,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing Secret within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_secrets_operations.py
|
_secrets_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._secrets_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SecretsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`secrets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.Secret"]:
"""Lists existing AzureFrontDoor secrets.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Secret or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecretListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SecretListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets"} # type: ignore
@distributed_trace_async
async def get(self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any) -> _models.Secret:
"""Gets an existing Secret within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Secret or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Secret
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> _models.Secret:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(secret, (IO, bytes)):
_content = secret
else:
_json = self._serialize.body(secret, "Secret")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Secret", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: _models.Secret,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: ~azure.mgmt.cdn.models.Secret
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Secret or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Required.
:type secret: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Secret or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
secret_name: str,
secret: Union[_models.Secret, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Secret]:
"""Creates a new Secret within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:param secret: The Secret properties. Is either a model type or a IO type. Required.
:type secret: ~azure.mgmt.cdn.models.Secret or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Secret or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Secret]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Secret]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
secret=secret,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Secret", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, secret_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing Secret within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param secret_name: Name of the Secret under the profile. Required.
:type secret_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
secret_name=secret_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"} # type: ignore
| 0.886402 | 0.089694 |
import datetime
from typing import Any, Callable, Dict, List, Optional, TypeVar, Union
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._log_analytics_operations import (
build_get_log_analytics_locations_request,
build_get_log_analytics_metrics_request,
build_get_log_analytics_rankings_request,
build_get_log_analytics_resources_request,
build_get_waf_log_analytics_metrics_request,
build_get_waf_log_analytics_rankings_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class LogAnalyticsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`log_analytics` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace_async
async def get_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.LogMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.LogMetricsGranularity],
custom_domains: List[str],
protocols: List[str],
group_by: Optional[List[Union[str, _models.LogMetricsGroupBy]]] = None,
continents: Optional[List[str]] = None,
country_or_regions: Optional[List[str]] = None,
**kwargs: Any
) -> _models.MetricsResponse:
"""Get log report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.LogMetricsGranularity
:param custom_domains: Required.
:type custom_domains: list[str]
:param protocols: Required.
:type protocols: list[str]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.LogMetricsGroupBy]
:param continents: Default value is None.
:type continents: list[str]
:param country_or_regions: Default value is None.
:type country_or_regions: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.MetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.MetricsResponse]
request = build_get_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
custom_domains=custom_domains,
protocols=protocols,
group_by=group_by,
continents=continents,
country_or_regions=country_or_regions,
api_version=api_version,
template_url=self.get_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("MetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsMetrics"} # type: ignore
@distributed_trace_async
async def get_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
rankings: List[Union[str, _models.LogRanking]],
metrics: List[Union[str, _models.LogRankingMetric]],
max_ranking: int,
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
custom_domains: Optional[List[str]] = None,
**kwargs: Any
) -> _models.RankingsResponse:
"""Get log analytics ranking report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.LogRanking]
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogRankingMetric]
:param max_ranking: Required.
:type max_ranking: int
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param custom_domains: Default value is None.
:type custom_domains: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RankingsResponse]
request = build_get_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
rankings=rankings,
metrics=metrics,
max_ranking=max_ranking,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
custom_domains=custom_domains,
api_version=api_version,
template_url=self.get_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsRankings"} # type: ignore
@distributed_trace_async
async def get_log_analytics_locations(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ContinentsResponse:
"""Get all available location names for AFD log analytics report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ContinentsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ContinentsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ContinentsResponse]
request = build_get_log_analytics_locations_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_locations.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ContinentsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_locations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsLocations"} # type: ignore
@distributed_trace_async
async def get_log_analytics_resources(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ResourcesResponse:
"""Get all endpoints and custom domains available for AFD log report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ResourcesResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ResourcesResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourcesResponse]
request = build_get_log_analytics_resources_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_resources.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ResourcesResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_resources.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsResources"} # type: ignore
@distributed_trace_async
async def get_waf_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.WafGranularity],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
group_by: Optional[List[Union[str, _models.WafRankingGroupBy]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafMetricsResponse:
"""Get Waf related log analytics report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.WafGranularity
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.WafRankingGroupBy]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafMetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafMetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafMetricsResponse]
request = build_get_waf_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
actions=actions,
group_by=group_by,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafMetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsMetrics"} # type: ignore
@distributed_trace_async
async def get_waf_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
max_ranking: int,
rankings: List[Union[str, _models.WafRankingType]],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafRankingsResponse:
"""Get WAF log analytics charts for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param max_ranking: Required.
:type max_ranking: int
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.WafRankingType]
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafRankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafRankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafRankingsResponse]
request = build_get_waf_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
max_ranking=max_ranking,
rankings=rankings,
actions=actions,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafRankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsRankings"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_log_analytics_operations.py
|
_log_analytics_operations.py
|
import datetime
from typing import Any, Callable, Dict, List, Optional, TypeVar, Union
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._log_analytics_operations import (
build_get_log_analytics_locations_request,
build_get_log_analytics_metrics_request,
build_get_log_analytics_rankings_request,
build_get_log_analytics_resources_request,
build_get_waf_log_analytics_metrics_request,
build_get_waf_log_analytics_rankings_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class LogAnalyticsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`log_analytics` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace_async
async def get_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.LogMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.LogMetricsGranularity],
custom_domains: List[str],
protocols: List[str],
group_by: Optional[List[Union[str, _models.LogMetricsGroupBy]]] = None,
continents: Optional[List[str]] = None,
country_or_regions: Optional[List[str]] = None,
**kwargs: Any
) -> _models.MetricsResponse:
"""Get log report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.LogMetricsGranularity
:param custom_domains: Required.
:type custom_domains: list[str]
:param protocols: Required.
:type protocols: list[str]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.LogMetricsGroupBy]
:param continents: Default value is None.
:type continents: list[str]
:param country_or_regions: Default value is None.
:type country_or_regions: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.MetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.MetricsResponse]
request = build_get_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
custom_domains=custom_domains,
protocols=protocols,
group_by=group_by,
continents=continents,
country_or_regions=country_or_regions,
api_version=api_version,
template_url=self.get_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("MetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsMetrics"} # type: ignore
@distributed_trace_async
async def get_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
rankings: List[Union[str, _models.LogRanking]],
metrics: List[Union[str, _models.LogRankingMetric]],
max_ranking: int,
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
custom_domains: Optional[List[str]] = None,
**kwargs: Any
) -> _models.RankingsResponse:
"""Get log analytics ranking report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.LogRanking]
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.LogRankingMetric]
:param max_ranking: Required.
:type max_ranking: int
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param custom_domains: Default value is None.
:type custom_domains: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RankingsResponse]
request = build_get_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
rankings=rankings,
metrics=metrics,
max_ranking=max_ranking,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
custom_domains=custom_domains,
api_version=api_version,
template_url=self.get_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsRankings"} # type: ignore
@distributed_trace_async
async def get_log_analytics_locations(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ContinentsResponse:
"""Get all available location names for AFD log analytics report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ContinentsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ContinentsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ContinentsResponse]
request = build_get_log_analytics_locations_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_locations.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ContinentsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_locations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsLocations"} # type: ignore
@distributed_trace_async
async def get_log_analytics_resources(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.ResourcesResponse:
"""Get all endpoints and custom domains available for AFD log report.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ResourcesResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ResourcesResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourcesResponse]
request = build_get_log_analytics_resources_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_log_analytics_resources.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ResourcesResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_log_analytics_resources.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getLogAnalyticsResources"} # type: ignore
@distributed_trace_async
async def get_waf_log_analytics_metrics(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
granularity: Union[str, _models.WafGranularity],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
group_by: Optional[List[Union[str, _models.WafRankingGroupBy]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafMetricsResponse:
"""Get Waf related log analytics report for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param granularity: Known values are: "PT5M", "PT1H", and "P1D". Required.
:type granularity: str or ~azure.mgmt.cdn.models.WafGranularity
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param group_by: Default value is None.
:type group_by: list[str or ~azure.mgmt.cdn.models.WafRankingGroupBy]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafMetricsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafMetricsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafMetricsResponse]
request = build_get_waf_log_analytics_metrics_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
granularity=granularity,
actions=actions,
group_by=group_by,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_metrics.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafMetricsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_metrics.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsMetrics"} # type: ignore
@distributed_trace_async
async def get_waf_log_analytics_rankings(
self,
resource_group_name: str,
profile_name: str,
metrics: List[Union[str, _models.WafMetric]],
date_time_begin: datetime.datetime,
date_time_end: datetime.datetime,
max_ranking: int,
rankings: List[Union[str, _models.WafRankingType]],
actions: Optional[List[Union[str, _models.WafAction]]] = None,
rule_types: Optional[List[Union[str, _models.WafRuleType]]] = None,
**kwargs: Any
) -> _models.WafRankingsResponse:
"""Get WAF log analytics charts for AFD profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. which is unique within the resource group. Required.
:type profile_name: str
:param metrics: Required.
:type metrics: list[str or ~azure.mgmt.cdn.models.WafMetric]
:param date_time_begin: Required.
:type date_time_begin: ~datetime.datetime
:param date_time_end: Required.
:type date_time_end: ~datetime.datetime
:param max_ranking: Required.
:type max_ranking: int
:param rankings: Required.
:type rankings: list[str or ~azure.mgmt.cdn.models.WafRankingType]
:param actions: Default value is None.
:type actions: list[str or ~azure.mgmt.cdn.models.WafAction]
:param rule_types: Default value is None.
:type rule_types: list[str or ~azure.mgmt.cdn.models.WafRuleType]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: WafRankingsResponse or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.WafRankingsResponse
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.WafRankingsResponse]
request = build_get_waf_log_analytics_rankings_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
metrics=metrics,
date_time_begin=date_time_begin,
date_time_end=date_time_end,
max_ranking=max_ranking,
rankings=rankings,
actions=actions,
rule_types=rule_types,
api_version=api_version,
template_url=self.get_waf_log_analytics_rankings.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("WafRankingsResponse", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_waf_log_analytics_rankings.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getWafLogAnalyticsRankings"} # type: ignore
| 0.87724 | 0.089574 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_custom_domains_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_refresh_validation_token_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDCustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDDomain"]:
"""Lists existing AzureFrontDoor domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
or CDN profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDDomain or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.AFDDomain:
"""Gets an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain, (IO, bytes)):
_content = custom_domain
else:
_json = self._serialize.body(custom_domain, "AFDDomain")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: _models.AFDDomain,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Is either a model type or a IO type. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain=custom_domain,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_update_properties, (IO, bytes)):
_content = custom_domain_update_properties
else:
_json = self._serialize.body(custom_domain_update_properties, "AFDDomainUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: _models.AFDDomainUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Is either a model type or a IO type.
Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain_update_properties=custom_domain_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _refresh_validation_token_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_refresh_validation_token_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._refresh_validation_token_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_refresh_validation_token_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
@distributed_trace_async
async def begin_refresh_validation_token(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Updates the domain validation token.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._refresh_validation_token_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_refresh_validation_token.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_afd_custom_domains_operations.py
|
_afd_custom_domains_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_custom_domains_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_refresh_validation_token_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDCustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDDomain"]:
"""Lists existing AzureFrontDoor domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
or CDN profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDDomain or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.AFDDomain:
"""Gets an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain, (IO, bytes)):
_content = custom_domain
else:
_json = self._serialize.body(custom_domain, "AFDDomain")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: _models.AFDDomain,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Required.
:type custom_domain: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain: Union[_models.AFDDomain, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Creates a new domain within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain: Domain properties. Is either a model type or a IO type. Required.
:type custom_domain: ~azure.mgmt.cdn.models.AFDDomain or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain=custom_domain,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_update_properties, (IO, bytes)):
_content = custom_domain_update_properties
else:
_json = self._serialize.body(custom_domain_update_properties, "AFDDomainUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: _models.AFDDomainUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Required.
:type custom_domain_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
custom_domain_name: str,
custom_domain_update_properties: Union[_models.AFDDomainUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDDomain]:
"""Updates an existing domain within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:param custom_domain_update_properties: Domain properties. Is either a model type or a IO type.
Required.
:type custom_domain_update_properties: ~azure.mgmt.cdn.models.AFDDomainUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
custom_domain_update_properties=custom_domain_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing AzureFrontDoor domain with the specified domain name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}"} # type: ignore
async def _refresh_validation_token_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_refresh_validation_token_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._refresh_validation_token_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_refresh_validation_token_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
@distributed_trace_async
async def begin_refresh_validation_token(
self, resource_group_name: str, profile_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Updates the domain validation token.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param custom_domain_name: Name of the domain under the profile which is unique globally.
Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._refresh_validation_token_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_refresh_validation_token.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}/refreshValidationToken"} # type: ignore
| 0.904527 | 0.075858 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._origins_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_endpoint_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class OriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.Origin"]:
"""Lists all of the existing origins within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Origin or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> _models.Origin:
"""Gets an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Origin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Origin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "Origin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: _models.Origin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.Origin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.Origin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "OriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: _models.OriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_origins_operations.py
|
_origins_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._origins_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_endpoint_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class OriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.Origin"]:
"""Lists all of the existing origins within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Origin or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> _models.Origin:
"""Gets an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Origin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Origin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "Origin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: _models.Origin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.Origin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin: Union[_models.Origin, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Creates a new origin within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin that is unique within the endpoint. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.Origin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> _models.Origin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "OriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Origin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: _models.OriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_name: str,
origin_update_properties: Union[_models.OriginUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Origin]:
"""Updates an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.OriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Origin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Origin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Origin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Origin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_name: Name of the origin which is unique within the endpoint. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}"} # type: ignore
| 0.904627 | 0.093719 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._routes_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_endpoint_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class RoutesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`routes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.Route"]:
"""Lists all of the existing origins within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Route or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("RouteListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> _models.Route:
"""Gets an existing route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Route or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Route
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route, (IO, bytes)):
_content = route
else:
_json = self._serialize.body(route, "Route")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: _models.Route,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: ~azure.mgmt.cdn.models.Route
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Is either a model type or a IO type. Required.
:type route: ~azure.mgmt.cdn.models.Route or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route=route,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route_update_properties, (IO, bytes)):
_content = route_update_properties
else:
_json = self._serialize.body(route_update_properties, "RouteUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: _models.RouteUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Is either a model type or a IO type.
Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route_update_properties=route_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_routes_operations.py
|
_routes_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._routes_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_endpoint_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class RoutesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`routes` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.Route"]:
"""Lists all of the existing origins within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Route or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("RouteListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> _models.Route:
"""Gets an existing route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Route or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Route
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route, (IO, bytes)):
_content = route
else:
_json = self._serialize.body(route, "Route")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: _models.Route,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: ~azure.mgmt.cdn.models.Route
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Required.
:type route: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route: Union[_models.Route, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Creates a new route with the specified route name under the specified subscription, resource
group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route: Route properties. Is either a model type or a IO type. Required.
:type route: ~azure.mgmt.cdn.models.Route or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route=route,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> _models.Route:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(route_update_properties, (IO, bytes)):
_content = route_update_properties
else:
_json = self._serialize.body(route_update_properties, "RouteUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Route", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: _models.RouteUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Required.
:type route_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
route_name: str,
route_update_properties: Union[_models.RouteUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Route]:
"""Updates an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:param route_update_properties: Route update properties. Is either a model type or a IO type.
Required.
:type route_update_properties: ~azure.mgmt.cdn.models.RouteUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Route or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Route]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Route]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
route_update_properties=route_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Route", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, route_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing route with the specified route name under the specified subscription,
resource group, profile, and AzureFrontDoor endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param route_name: Name of the routing rule. Required.
:type route_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
route_name=route_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/routes/{routeName}"} # type: ignore
| 0.907858 | 0.07579 |
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._managed_rule_sets_operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ManagedRuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`managed_rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.ManagedRuleSetDefinition"]:
"""Lists all available managed rule sets.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ManagedRuleSetDefinition or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ManagedRuleSetDefinition]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagedRuleSetDefinitionList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedRuleSetDefinitionList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/cdnWebApplicationFirewallManagedRuleSets"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_managed_rule_sets_operations.py
|
_managed_rule_sets_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._managed_rule_sets_operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ManagedRuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`managed_rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.ManagedRuleSetDefinition"]:
"""Lists all available managed rule sets.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ManagedRuleSetDefinition or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ManagedRuleSetDefinition]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ManagedRuleSetDefinitionList]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedRuleSetDefinitionList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/cdnWebApplicationFirewallManagedRuleSets"} # type: ignore
| 0.86421 | 0.090816 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_endpoints_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
build_purge_content_request,
build_update_request,
build_validate_custom_domain_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDEndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDEndpoint"]:
"""Lists existing AzureFrontDoor endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDEndpoint or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDEndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.AFDEndpoint:
"""Gets an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDEndpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDEndpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "AFDEndpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.AFDEndpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "AFDEndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.AFDEndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(contents, (IO, bytes)):
_content = contents
else:
_json = self._serialize.body(contents, "AfdPurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: _models.AfdPurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory. Is
either a model type or a IO type. Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
contents=contents,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor endpoint under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/usages"} # type: ignore
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/validateCustomDomain"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_afd_endpoints_operations.py
|
_afd_endpoints_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_endpoints_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
build_purge_content_request,
build_update_request,
build_validate_custom_domain_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDEndpointsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_endpoints` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDEndpoint"]:
"""Lists existing AzureFrontDoor endpoints.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDEndpoint or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpointListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDEndpointListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> _models.AFDEndpoint:
"""Gets an existing AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDEndpoint or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDEndpoint
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint, (IO, bytes)):
_content = endpoint
else:
_json = self._serialize.body(endpoint, "AFDEndpoint")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: _models.AFDEndpoint,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Required.
:type endpoint: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint: Union[_models.AFDEndpoint, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Creates a new AzureFrontDoor endpoint with the specified endpoint name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint: Endpoint properties. Is either a model type or a IO type. Required.
:type endpoint: ~azure.mgmt.cdn.models.AFDEndpoint or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint=endpoint,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDEndpoint:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(endpoint_update_properties, (IO, bytes)):
_content = endpoint_update_properties
else:
_json = self._serialize.body(endpoint_update_properties, "AFDEndpointUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: _models.AFDEndpointUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Required.
:type endpoint_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
endpoint_update_properties: Union[_models.AFDEndpointUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDEndpoint]:
"""Updates an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile. Only tags can be updated after creating an
endpoint. To update origins, use the Update Origin operation. To update origin groups, use the
Update Origin group operation. To update domains, use the Update Custom Domain operation.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param endpoint_update_properties: Endpoint update properties. Is either a model type or a IO
type. Required.
:type endpoint_update_properties: ~azure.mgmt.cdn.models.AFDEndpointUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDEndpoint or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDEndpoint]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDEndpoint]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
endpoint_update_properties=endpoint_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDEndpoint", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing AzureFrontDoor endpoint with the specified endpoint name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}"} # type: ignore
async def _purge_content_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(contents, (IO, bytes)):
_content = contents
else:
_json = self._serialize.body(contents, "AfdPurgeParameters")
request = build_purge_content_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._purge_content_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_purge_content_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: _models.AfdPurgeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory.
Required.
:type contents: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_purge_content(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
contents: Union[_models.AfdPurgeParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Removes a content from AzureFrontDoor.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param contents: The list of paths to the content and the list of linked domains to be purged.
Path can be a full URL, e.g. '/pictures/city.png' which removes a single file, or a directory
with a wildcard, e.g. '/pictures/*' which removes all folders and files in the directory. Is
either a model type or a IO type. Required.
:type contents: ~azure.mgmt.cdn.models.AfdPurgeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._purge_content_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
contents=contents,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_purge_content.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/purge"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor endpoint under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/usages"} # type: ignore
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: _models.ValidateCustomDomainInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_custom_domain(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_properties: Union[_models.ValidateCustomDomainInput, IO],
**kwargs: Any
) -> _models.ValidateCustomDomainOutput:
"""Validates the custom domain mapping to ensure it maps to the correct CDN endpoint in DNS.This
api isn't work for apex domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_properties: Custom domain to be validated. Is either a model type or a IO
type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.ValidateCustomDomainInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateCustomDomainOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateCustomDomainOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateCustomDomainOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "ValidateCustomDomainInput")
request = build_validate_custom_domain_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_custom_domain.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateCustomDomainOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_custom_domain.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/afdEndpoints/{endpointName}/validateCustomDomain"} # type: ignore
| 0.883895 | 0.10026 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._rules_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_rule_set_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class RulesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`rules` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_rule_set(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> AsyncIterable["_models.Rule"]:
"""Lists all of the existing delivery rules within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Rule or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_rule_set_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_rule_set.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("RuleListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> _models.Rule:
"""Gets an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Rule or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Rule
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule, (IO, bytes)):
_content = rule
else:
_json = self._serialize.body(rule, "Rule")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: _models.Rule,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: ~azure.mgmt.cdn.models.Rule
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Is either a model type or a IO type. Required.
:type rule: ~azure.mgmt.cdn.models.Rule or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule=rule,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule_update_properties, (IO, bytes)):
_content = rule_update_properties
else:
_json = self._serialize.body(rule_update_properties, "RuleUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: _models.RuleUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Is either a model type or a IO type.
Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule_update_properties=rule_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_rules_operations.py
|
_rules_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._rules_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_rule_set_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class RulesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`rules` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_rule_set(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> AsyncIterable["_models.Rule"]:
"""Lists all of the existing delivery rules within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Rule or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_rule_set_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_rule_set.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("RuleListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> _models.Rule:
"""Gets an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Rule or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Rule
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule, (IO, bytes)):
_content = rule
else:
_json = self._serialize.body(rule, "Rule")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: _models.Rule,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: ~azure.mgmt.cdn.models.Rule
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Required.
:type rule: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule: Union[_models.Rule, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Creates a new delivery rule within the specified rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule: The delivery rule properties. Is either a model type or a IO type. Required.
:type rule: ~azure.mgmt.cdn.models.Rule or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule=rule,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> _models.Rule:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(rule_update_properties, (IO, bytes)):
_content = rule_update_properties
else:
_json = self._serialize.body(rule_update_properties, "RuleUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Rule", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: _models.RuleUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Required.
:type rule_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
rule_set_name: str,
rule_name: str,
rule_update_properties: Union[_models.RuleUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Rule]:
"""Updates an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:param rule_update_properties: Delivery rule properties. Is either a model type or a IO type.
Required.
:type rule_update_properties: ~azure.mgmt.cdn.models.RuleUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Rule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Rule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Rule]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
rule_update_properties=rule_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Rule", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, rule_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing delivery rule within a rule set.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile. Required.
:type rule_set_name: str
:param rule_name: Name of the delivery rule which is unique within the endpoint. Required.
:type rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
rule_name=rule_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/rules/{ruleName}"} # type: ignore
| 0.892753 | 0.09343 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_profiles_operations import (
build_check_host_name_availability_request,
build_list_resource_usage_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of AzureFrontDoor endpoints under the given CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/usages"} # type: ignore
@overload
async def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: _models.CheckHostNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: Union[_models.CheckHostNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Is either a model
type or a IO type. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_host_name_availability_input, (IO, bytes)):
_content = check_host_name_availability_input
else:
_json = self._serialize.body(check_host_name_availability_input, "CheckHostNameAvailabilityInput")
request = build_check_host_name_availability_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_host_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_host_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkHostNameAvailability"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_afd_profiles_operations.py
|
_afd_profiles_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_profiles_operations import (
build_check_host_name_availability_request,
build_list_resource_usage_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of AzureFrontDoor endpoints under the given CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/usages"} # type: ignore
@overload
async def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: _models.CheckHostNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Required.
:type check_host_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_host_name_availability(
self,
resource_group_name: str,
profile_name: str,
check_host_name_availability_input: Union[_models.CheckHostNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the name availability of a host name.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param check_host_name_availability_input: Custom domain to be validated. Is either a model
type or a IO type. Required.
:type check_host_name_availability_input: ~azure.mgmt.cdn.models.CheckHostNameAvailabilityInput
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_host_name_availability_input, (IO, bytes)):
_content = check_host_name_availability_input
else:
_json = self._serialize.body(check_host_name_availability_input, "CheckHostNameAvailabilityInput")
request = build_check_host_name_availability_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_host_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_host_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkHostNameAvailability"} # type: ignore
| 0.889108 | 0.084871 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._custom_domains_operations import (
build_create_request,
build_delete_request,
build_disable_custom_https_request,
build_enable_custom_https_request,
build_get_request,
build_list_by_endpoint_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class CustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.CustomDomain"]:
"""Lists all of the existing custom domains within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CustomDomain or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("CustomDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
"""Gets an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CustomDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CustomDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "CustomDomainParameters")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: _models.CustomDomainParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Is either a
model type or a IO type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_properties=custom_domain_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
async def _delete_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> Optional[_models.CustomDomain]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CustomDomain]]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
async def _disable_custom_https_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_disable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._disable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_disable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
@distributed_trace_async
async def begin_disable_custom_https(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Disable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._disable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_disable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
async def _enable_custom_https_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_https_parameters, (IO, bytes)):
_content = custom_domain_https_parameters
else:
if custom_domain_https_parameters is not None:
_json = self._serialize.body(custom_domain_https_parameters, "CustomDomainHttpsParameters")
else:
_json = None
request = build_enable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._enable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_enable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
@overload
async def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[_models.CustomDomainHttpsParameters] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[IO] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Is either a model type or a IO type.
Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._enable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_https_parameters=custom_domain_https_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_enable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_custom_domains_operations.py
|
_custom_domains_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._custom_domains_operations import (
build_create_request,
build_delete_request,
build_disable_custom_https_request,
build_enable_custom_https_request,
build_get_request,
build_list_by_endpoint_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class CustomDomainsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`custom_domains` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.CustomDomain"]:
"""Lists all of the existing custom domains within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either CustomDomain or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomainListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("CustomDomainListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
"""Gets an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CustomDomain or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CustomDomain
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_properties, (IO, bytes)):
_content = custom_domain_properties
else:
_json = self._serialize.body(custom_domain_properties, "CustomDomainParameters")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: _models.CustomDomainParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Required.
:type custom_domain_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_properties: Union[_models.CustomDomainParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Creates a new custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_properties: Properties required to create a new custom domain. Is either a
model type or a IO type. Required.
:type custom_domain_properties: ~azure.mgmt.cdn.models.CustomDomainParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_properties=custom_domain_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
async def _delete_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> Optional[_models.CustomDomain]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CustomDomain]]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing custom domain within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}"} # type: ignore
async def _disable_custom_https_initial(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
request = build_disable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._disable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_disable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
@distributed_trace_async
async def begin_disable_custom_https(
self, resource_group_name: str, profile_name: str, endpoint_name: str, custom_domain_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Disable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._disable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_disable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/disableCustomHttps"} # type: ignore
async def _enable_custom_https_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> _models.CustomDomain:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(custom_domain_https_parameters, (IO, bytes)):
_content = custom_domain_https_parameters
else:
if custom_domain_https_parameters is not None:
_json = self._serialize.body(custom_domain_https_parameters, "CustomDomainHttpsParameters")
else:
_json = None
request = build_enable_custom_https_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._enable_custom_https_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_enable_custom_https_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
@overload
async def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[_models.CustomDomainHttpsParameters] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[IO] = None,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Default value is None.
:type custom_domain_https_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_enable_custom_https(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
custom_domain_name: str,
custom_domain_https_parameters: Optional[Union[_models.CustomDomainHttpsParameters, IO]] = None,
**kwargs: Any
) -> AsyncLROPoller[_models.CustomDomain]:
"""Enable https delivery of the custom domain.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param custom_domain_name: Name of the custom domain within an endpoint. Required.
:type custom_domain_name: str
:param custom_domain_https_parameters: The configuration specifying how to enable HTTPS for the
custom domain - using CDN managed certificate or user's own certificate. If not specified,
enabling ssl uses CDN managed certificate by default. Is either a model type or a IO type.
Default value is None.
:type custom_domain_https_parameters: ~azure.mgmt.cdn.models.CustomDomainHttpsParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either CustomDomain or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.CustomDomain]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._enable_custom_https_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
custom_domain_name=custom_domain_name,
custom_domain_https_parameters=custom_domain_https_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("CustomDomain", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_enable_custom_https.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}/enableCustomHttps"} # type: ignore
| 0.899381 | 0.075892 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._origin_groups_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_endpoint_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class OriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.OriginGroup"]:
"""Lists all of the existing origin groups within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OriginGroup or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> _models.OriginGroup:
"""Gets an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: OriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.OriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "OriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: _models.OriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "OriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: _models.OriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_origin_groups_operations.py
|
_origin_groups_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._origin_groups_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_endpoint_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class OriginGroupsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`origin_groups` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_endpoint(
self, resource_group_name: str, profile_name: str, endpoint_name: str, **kwargs: Any
) -> AsyncIterable["_models.OriginGroup"]:
"""Lists all of the existing origin groups within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either OriginGroup or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroupListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_endpoint_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_endpoint.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OriginGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_endpoint.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> _models.OriginGroup:
"""Gets an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: OriginGroup or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.OriginGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group, (IO, bytes)):
_content = origin_group
else:
_json = self._serialize.body(origin_group, "OriginGroup")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: _models.OriginGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Required.
:type origin_group: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group: Union[_models.OriginGroup, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Creates a new origin group within the specified endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group: Origin group properties. Is either a model type or a IO type. Required.
:type origin_group: ~azure.mgmt.cdn.models.OriginGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group=origin_group,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> _models.OriginGroup:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_group_update_properties, (IO, bytes)):
_content = origin_group_update_properties
else:
_json = self._serialize.body(origin_group_update_properties, "OriginGroupUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: _models.OriginGroupUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Required.
:type origin_group_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
endpoint_name: str,
origin_group_name: str,
origin_group_update_properties: Union[_models.OriginGroupUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.OriginGroup]:
"""Updates an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:param origin_group_update_properties: Origin group properties. Is either a model type or a IO
type. Required.
:type origin_group_update_properties: ~azure.mgmt.cdn.models.OriginGroupUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either OriginGroup or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.OriginGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.OriginGroup]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
origin_group_update_properties=origin_group_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("OriginGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, endpoint_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin group within an endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:param endpoint_name: Name of the endpoint under the profile which is unique globally.
Required.
:type endpoint_name: str
:param origin_group_name: Name of the origin group which is unique within the endpoint.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
endpoint_name=endpoint_name,
origin_group_name=origin_group_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/originGroups/{originGroupName}"} # type: ignore
| 0.905082 | 0.084342 |
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._cdn_management_client_operations import (
build_check_endpoint_name_availability_request,
build_check_name_availability_request,
build_check_name_availability_with_subscription_request,
build_validate_probe_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class CdnManagementClientOperationsMixin(MixinABC):
@overload
async def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: _models.CheckEndpointNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: Union[_models.CheckEndpointNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Is either a model type or a IO
type. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckEndpointNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_endpoint_name_availability_input, (IO, bytes)):
_content = check_endpoint_name_availability_input
else:
_json = self._serialize.body(check_endpoint_name_availability_input, "CheckEndpointNameAvailabilityInput")
request = build_check_endpoint_name_availability_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_endpoint_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckEndpointNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_endpoint_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/checkEndpointNameAvailability"} # type: ignore
@overload
async def check_name_availability(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_name_availability(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_name_availability(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability.metadata = {"url": "/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
async def check_name_availability_with_subscription(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_name_availability_with_subscription(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_name_availability_with_subscription(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_with_subscription_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability_with_subscription.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability_with_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
async def validate_probe(
self, validate_probe_input: _models.ValidateProbeInput, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_probe(
self, validate_probe_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_probe(
self, validate_probe_input: Union[_models.ValidateProbeInput, IO], **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Is either a model type or a IO type. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProbeOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_probe_input, (IO, bytes)):
_content = validate_probe_input
else:
_json = self._serialize.body(validate_probe_input, "ValidateProbeInput")
request = build_validate_probe_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_probe.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateProbeOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_probe.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_cdn_management_client_operations.py
|
_cdn_management_client_operations.py
|
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._cdn_management_client_operations import (
build_check_endpoint_name_availability_request,
build_check_name_availability_request,
build_check_name_availability_with_subscription_request,
build_validate_probe_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class CdnManagementClientOperationsMixin(MixinABC):
@overload
async def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: _models.CheckEndpointNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Required.
:type check_endpoint_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_endpoint_name_availability(
self,
resource_group_name: str,
check_endpoint_name_availability_input: Union[_models.CheckEndpointNameAvailabilityInput, IO],
**kwargs: Any
) -> _models.CheckEndpointNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a afdx endpoint.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param check_endpoint_name_availability_input: Input to check. Is either a model type or a IO
type. Required.
:type check_endpoint_name_availability_input:
~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckEndpointNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckEndpointNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckEndpointNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_endpoint_name_availability_input, (IO, bytes)):
_content = check_endpoint_name_availability_input
else:
_json = self._serialize.body(check_endpoint_name_availability_input, "CheckEndpointNameAvailabilityInput")
request = build_check_endpoint_name_availability_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_endpoint_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckEndpointNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_endpoint_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/checkEndpointNameAvailability"} # type: ignore
@overload
async def check_name_availability(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_name_availability(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_name_availability(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_request(
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability.metadata = {"url": "/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
async def check_name_availability_with_subscription(
self,
check_name_availability_input: _models.CheckNameAvailabilityInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def check_name_availability_with_subscription(
self, check_name_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Required.
:type check_name_availability_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def check_name_availability_with_subscription(
self, check_name_availability_input: Union[_models.CheckNameAvailabilityInput, IO], **kwargs: Any
) -> _models.CheckNameAvailabilityOutput:
"""Check the availability of a resource name. This is needed for resources where name is globally
unique, such as a CDN endpoint.
:param check_name_availability_input: Input to check. Is either a model type or a IO type.
Required.
:type check_name_availability_input: ~azure.mgmt.cdn.models.CheckNameAvailabilityInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckNameAvailabilityOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.CheckNameAvailabilityOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(check_name_availability_input, (IO, bytes)):
_content = check_name_availability_input
else:
_json = self._serialize.body(check_name_availability_input, "CheckNameAvailabilityInput")
request = build_check_name_availability_with_subscription_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.check_name_availability_with_subscription.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("CheckNameAvailabilityOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability_with_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/checkNameAvailability"} # type: ignore
@overload
async def validate_probe(
self, validate_probe_input: _models.ValidateProbeInput, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def validate_probe(
self, validate_probe_input: IO, *, content_type: str = "application/json", **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Required.
:type validate_probe_input: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def validate_probe(
self, validate_probe_input: Union[_models.ValidateProbeInput, IO], **kwargs: Any
) -> _models.ValidateProbeOutput:
"""Check if the probe path is a valid path and the file can be accessed. Probe path is the path to
a file hosted on the origin server to help accelerate the delivery of dynamic content via the
CDN endpoint. This path is relative to the origin path specified in the endpoint configuration.
:param validate_probe_input: Input to check. Is either a model type or a IO type. Required.
:type validate_probe_input: ~azure.mgmt.cdn.models.ValidateProbeInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ValidateProbeOutput or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.ValidateProbeOutput
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProbeOutput]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(validate_probe_input, (IO, bytes)):
_content = validate_probe_input
else:
_json = self._serialize.body(validate_probe_input, "ValidateProbeInput")
request = build_validate_probe_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.validate_probe.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ValidateProbeOutput", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
validate_probe.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe"} # type: ignore
| 0.878842 | 0.077204 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_origins_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_origin_group_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDOriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_origin_group(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDOrigin"]:
"""Lists all of the existing origins within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_origin_group_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_origin_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_origin_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> _models.AFDOrigin:
"""Gets an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOrigin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOrigin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "AFDOrigin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: _models.AFDOrigin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "AFDOriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: _models.AFDOriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_afd_origins_operations.py
|
_afd_origins_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._afd_origins_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_origin_group_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class AFDOriginsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`afd_origins` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_origin_group(
self, resource_group_name: str, profile_name: str, origin_group_name: str, **kwargs: Any
) -> AsyncIterable["_models.AFDOrigin"]:
"""Lists all of the existing origins within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AFDOrigin or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOriginListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_origin_group_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_origin_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("AFDOriginListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_origin_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> _models.AFDOrigin:
"""Gets an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AFDOrigin or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.AFDOrigin
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin, (IO, bytes)):
_content = origin
else:
_json = self._serialize.body(origin, "AFDOrigin")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: _models.AFDOrigin,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Required.
:type origin: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin: Union[_models.AFDOrigin, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Creates a new origin within the specified origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin that is unique within the profile. Required.
:type origin_name: str
:param origin: Origin properties. Is either a model type or a IO type. Required.
:type origin: ~azure.mgmt.cdn.models.AFDOrigin or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin=origin,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> _models.AFDOrigin:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(origin_update_properties, (IO, bytes)):
_content = origin_update_properties
else:
_json = self._serialize.body(origin_update_properties, "AFDOriginUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: _models.AFDOriginUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Required.
:type origin_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
origin_group_name: str,
origin_name: str,
origin_update_properties: Union[_models.AFDOriginUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.AFDOrigin]:
"""Updates an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:param origin_update_properties: Origin properties. Is either a model type or a IO type.
Required.
:type origin_update_properties: ~azure.mgmt.cdn.models.AFDOriginUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either AFDOrigin or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.AFDOrigin]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.AFDOrigin]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
origin_update_properties=origin_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("AFDOrigin", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, origin_group_name: str, origin_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing origin within an origin group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param origin_group_name: Name of the origin group which is unique within the profile.
Required.
:type origin_group_name: str
:param origin_name: Name of the origin which is unique within the profile. Required.
:type origin_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
origin_group_name=origin_group_name,
origin_name=origin_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}"} # type: ignore
| 0.913181 | 0.09645 |
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]:
"""Lists all of the available CDN REST API operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationsListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OperationsListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/operations"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_operations.py
|
_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._operations import build_list_request
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class Operations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`operations` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]:
"""Lists all of the available CDN REST API operations.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Operation or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Operation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationsListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("OperationsListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/providers/Microsoft.Cdn/operations"} # type: ignore
| 0.871283 | 0.095476 |
from ._cdn_management_client_operations import CdnManagementClientOperationsMixin
from ._afd_profiles_operations import AFDProfilesOperations
from ._afd_custom_domains_operations import AFDCustomDomainsOperations
from ._afd_endpoints_operations import AFDEndpointsOperations
from ._afd_origin_groups_operations import AFDOriginGroupsOperations
from ._afd_origins_operations import AFDOriginsOperations
from ._routes_operations import RoutesOperations
from ._rule_sets_operations import RuleSetsOperations
from ._rules_operations import RulesOperations
from ._security_policies_operations import SecurityPoliciesOperations
from ._secrets_operations import SecretsOperations
from ._validate_operations import ValidateOperations
from ._log_analytics_operations import LogAnalyticsOperations
from ._profiles_operations import ProfilesOperations
from ._endpoints_operations import EndpointsOperations
from ._origins_operations import OriginsOperations
from ._origin_groups_operations import OriginGroupsOperations
from ._custom_domains_operations import CustomDomainsOperations
from ._resource_usage_operations import ResourceUsageOperations
from ._operations import Operations
from ._edge_nodes_operations import EdgeNodesOperations
from ._policies_operations import PoliciesOperations
from ._managed_rule_sets_operations import ManagedRuleSetsOperations
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"CdnManagementClientOperationsMixin",
"AFDProfilesOperations",
"AFDCustomDomainsOperations",
"AFDEndpointsOperations",
"AFDOriginGroupsOperations",
"AFDOriginsOperations",
"RoutesOperations",
"RuleSetsOperations",
"RulesOperations",
"SecurityPoliciesOperations",
"SecretsOperations",
"ValidateOperations",
"LogAnalyticsOperations",
"ProfilesOperations",
"EndpointsOperations",
"OriginsOperations",
"OriginGroupsOperations",
"CustomDomainsOperations",
"ResourceUsageOperations",
"Operations",
"EdgeNodesOperations",
"PoliciesOperations",
"ManagedRuleSetsOperations",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/__init__.py
|
__init__.py
|
from ._cdn_management_client_operations import CdnManagementClientOperationsMixin
from ._afd_profiles_operations import AFDProfilesOperations
from ._afd_custom_domains_operations import AFDCustomDomainsOperations
from ._afd_endpoints_operations import AFDEndpointsOperations
from ._afd_origin_groups_operations import AFDOriginGroupsOperations
from ._afd_origins_operations import AFDOriginsOperations
from ._routes_operations import RoutesOperations
from ._rule_sets_operations import RuleSetsOperations
from ._rules_operations import RulesOperations
from ._security_policies_operations import SecurityPoliciesOperations
from ._secrets_operations import SecretsOperations
from ._validate_operations import ValidateOperations
from ._log_analytics_operations import LogAnalyticsOperations
from ._profiles_operations import ProfilesOperations
from ._endpoints_operations import EndpointsOperations
from ._origins_operations import OriginsOperations
from ._origin_groups_operations import OriginGroupsOperations
from ._custom_domains_operations import CustomDomainsOperations
from ._resource_usage_operations import ResourceUsageOperations
from ._operations import Operations
from ._edge_nodes_operations import EdgeNodesOperations
from ._policies_operations import PoliciesOperations
from ._managed_rule_sets_operations import ManagedRuleSetsOperations
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"CdnManagementClientOperationsMixin",
"AFDProfilesOperations",
"AFDCustomDomainsOperations",
"AFDEndpointsOperations",
"AFDOriginGroupsOperations",
"AFDOriginsOperations",
"RoutesOperations",
"RuleSetsOperations",
"RulesOperations",
"SecurityPoliciesOperations",
"SecretsOperations",
"ValidateOperations",
"LogAnalyticsOperations",
"ProfilesOperations",
"EndpointsOperations",
"OriginsOperations",
"OriginGroupsOperations",
"CustomDomainsOperations",
"ResourceUsageOperations",
"Operations",
"EdgeNodesOperations",
"PoliciesOperations",
"ManagedRuleSetsOperations",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
| 0.40157 | 0.054727 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._profiles_operations import (
build_create_request,
build_delete_request,
build_generate_sso_uri_request,
build_get_request,
build_list_by_resource_group_request,
build_list_request,
build_list_resource_usage_request,
build_list_supported_optimization_types_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within
an Azure subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace
def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within a
resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_resource_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace_async
async def get(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.Profile:
"""Gets an Azure Front Door Standard or Azure Front Door Premium or CDN profile with the specified
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Profile or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Profile
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
async def _create_initial(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile, (IO, bytes)):
_content = profile
else:
_json = self._serialize.body(profile, "Profile")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: _models.Profile,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: ~azure.mgmt.cdn.models.Profile
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Is either a model type or a
IO type. Required.
:type profile: ~azure.mgmt.cdn.models.Profile or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile=profile,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile_update_parameters, (IO, bytes)):
_content = profile_update_parameters
else:
_json = self._serialize.body(profile_update_parameters, "ProfileUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: _models.ProfileUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile. Is
either a model type or a IO type. Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile_update_parameters=profile_update_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace_async
async def begin_delete(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> AsyncLROPoller[None]:
"""Deletes an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified parameters. Deleting a profile will result in the deletion of all of the
sub-resources including endpoints, origins and custom domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace_async
async def generate_sso_uri(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.SsoUri:
"""Generates a dynamic SSO URI used to sign in to the CDN supplemental portal. Supplemental portal
is used to configure advanced feature capabilities that are not yet available in the Azure
portal, such as core reports in a standard profile; rules engine, advanced HTTP reports, and
real-time stats and alerts in a premium profile. The SSO URI changes approximately every 10
minutes.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SsoUri or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SsoUri
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SsoUri]
request = build_generate_sso_uri_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.generate_sso_uri.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SsoUri", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
generate_sso_uri.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/generateSsoUri"} # type: ignore
@distributed_trace_async
async def list_supported_optimization_types(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.SupportedOptimizationTypesListResult:
"""Gets the supported optimization types for the current profile. A user can create an endpoint
with an optimization type from the listed values.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SupportedOptimizationTypesListResult or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SupportedOptimizationTypesListResult
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedOptimizationTypesListResult]
request = build_list_supported_optimization_types_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_supported_optimization_types.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SupportedOptimizationTypesListResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_supported_optimization_types.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getSupportedOptimizationTypes"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.ResourceUsage"]:
"""Checks the quota and actual usage of endpoints under the given Azure Front Door Standard or
Azure Front Door Premium or CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkResourceUsage"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_profiles_operations.py
|
_profiles_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._profiles_operations import (
build_create_request,
build_delete_request,
build_generate_sso_uri_request,
build_get_request,
build_list_by_resource_group_request,
build_list_request,
build_list_resource_usage_request,
build_list_supported_optimization_types_request,
build_update_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ProfilesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`profiles` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(self, **kwargs: Any) -> AsyncIterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within
an Azure subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace
def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Profile"]:
"""Lists all of the Azure Front Door Standard, Azure Front Door Premium, and CDN profiles within a
resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Profile or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ProfileListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_resource_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ProfileListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles"} # type: ignore
@distributed_trace_async
async def get(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.Profile:
"""Gets an Azure Front Door Standard or Azure Front Door Premium or CDN profile with the specified
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Profile or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.Profile
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
async def _create_initial(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile, (IO, bytes)):
_content = profile
else:
_json = self._serialize.body(profile, "Profile")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: _models.Profile,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: ~azure.mgmt.cdn.models.Profile
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
profile: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Required.
:type profile: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self, resource_group_name: str, profile_name: str, profile: Union[_models.Profile, IO], **kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Creates a new Azure Front Door Standard or Azure Front Door Premium or CDN profile with a
profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile: Profile properties needed to create a new profile. Is either a model type or a
IO type. Required.
:type profile: ~azure.mgmt.cdn.models.Profile or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile=profile,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> _models.Profile:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(profile_update_parameters, (IO, bytes)):
_content = profile_update_parameters
else:
_json = self._serialize.body(profile_update_parameters, "ProfileUpdateParameters")
request = build_update_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("Profile", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: _models.ProfileUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile.
Required.
:type profile_update_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update(
self,
resource_group_name: str,
profile_name: str,
profile_update_parameters: Union[_models.ProfileUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.Profile]:
"""Updates an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified profile name under the specified subscription and resource group.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:param profile_update_parameters: Profile properties needed to update an existing profile. Is
either a model type or a IO type. Required.
:type profile_update_parameters: ~azure.mgmt.cdn.models.ProfileUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either Profile or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.Profile]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.Profile]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
profile_update_parameters=profile_update_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("Profile", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace_async
async def begin_delete(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> AsyncLROPoller[None]:
"""Deletes an existing Azure Front Door Standard or Azure Front Door Premium or CDN profile with
the specified parameters. Deleting a profile will result in the deletion of all of the
sub-resources including endpoints, origins and custom domains.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}"} # type: ignore
@distributed_trace_async
async def generate_sso_uri(self, resource_group_name: str, profile_name: str, **kwargs: Any) -> _models.SsoUri:
"""Generates a dynamic SSO URI used to sign in to the CDN supplemental portal. Supplemental portal
is used to configure advanced feature capabilities that are not yet available in the Azure
portal, such as core reports in a standard profile; rules engine, advanced HTTP reports, and
real-time stats and alerts in a premium profile. The SSO URI changes approximately every 10
minutes.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the CDN profile which is unique within the resource group.
Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SsoUri or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SsoUri
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SsoUri]
request = build_generate_sso_uri_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.generate_sso_uri.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SsoUri", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
generate_sso_uri.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/generateSsoUri"} # type: ignore
@distributed_trace_async
async def list_supported_optimization_types(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> _models.SupportedOptimizationTypesListResult:
"""Gets the supported optimization types for the current profile. A user can create an endpoint
with an optimization type from the listed values.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SupportedOptimizationTypesListResult or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SupportedOptimizationTypesListResult
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SupportedOptimizationTypesListResult]
request = build_list_supported_optimization_types_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_supported_optimization_types.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SupportedOptimizationTypesListResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_supported_optimization_types.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/getSupportedOptimizationTypes"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.ResourceUsage"]:
"""Checks the quota and actual usage of endpoints under the given Azure Front Door Standard or
Azure Front Door Premium or CDN profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium or CDN
profile which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ResourceUsage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.ResourceUsage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.ResourceUsageListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ResourceUsageListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/checkResourceUsage"} # type: ignore
| 0.894381 | 0.090013 |
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._rule_sets_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class RuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.RuleSet"]:
"""Lists existing AzureFrontDoor rule sets within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either RuleSet or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.RuleSet]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSetListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("RuleSetListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> _models.RuleSet:
"""Gets an existing AzureFrontDoor rule set with the specified rule set name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace_async
async def create(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> _models.RuleSet:
"""Creates a new rule set within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.create.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("RuleSet", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing AzureFrontDoor rule set with the specified rule set name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor rule set under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/usages"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_rule_sets_operations.py
|
_rule_sets_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._rule_sets_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_list_resource_usage_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class RuleSetsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`rule_sets` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.RuleSet"]:
"""Lists existing AzureFrontDoor rule sets within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either RuleSet or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.RuleSet]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSetListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("RuleSetListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> _models.RuleSet:
"""Gets an existing AzureFrontDoor rule set with the specified rule set name under the specified
subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace_async
async def create(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> _models.RuleSet:
"""Creates a new rule set within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: RuleSet or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.RuleSet
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.RuleSet]
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.create.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("RuleSet", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("RuleSet", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing AzureFrontDoor rule set with the specified rule set name under the
specified subscription, resource group and profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}"} # type: ignore
@distributed_trace
def list_resource_usage(
self, resource_group_name: str, profile_name: str, rule_set_name: str, **kwargs: Any
) -> AsyncIterable["_models.Usage"]:
"""Checks the quota and actual usage of the given AzureFrontDoor rule set under the given CDN
profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param rule_set_name: Name of the rule set under the profile which is unique globally.
Required.
:type rule_set_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either Usage or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.Usage]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.UsagesListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_resource_usage_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
rule_set_name=rule_set_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_resource_usage.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("UsagesListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_resource_usage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/ruleSets/{ruleSetName}/usages"} # type: ignore
| 0.899517 | 0.095729 |
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._security_policies_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_patch_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SecurityPoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`security_policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.SecurityPolicy"]:
"""Lists security policies associated with the profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SecurityPolicy or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicyListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SecurityPolicyListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> _models.SecurityPolicy:
"""Gets an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SecurityPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SecurityPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy, (IO, bytes)):
_content = security_policy
else:
_json = self._serialize.body(security_policy, "SecurityPolicy")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: _models.SecurityPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Is either a model type or a IO type.
Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy=security_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
async def _patch_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy_update_properties, (IO, bytes)):
_content = security_policy_update_properties
else:
_json = self._serialize.body(security_policy_update_properties, "SecurityPolicyUpdateParameters")
request = build_patch_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._patch_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_patch_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
async def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: _models.SecurityPolicyUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Is either a model
type or a IO type. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._patch_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy_update_properties=security_policy_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_patch.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing security policy within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
|
azure-mgmt-cdn
|
/azure_mgmt_cdn-12.1.0b1-py3-none-any.whl/azure/mgmt/cdn/aio/operations/_security_policies_operations.py
|
_security_policies_operations.py
|
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._security_policies_operations import (
build_create_request,
build_delete_request,
build_get_request,
build_list_by_profile_request,
build_patch_request,
)
from .._vendor import MixinABC
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SecurityPoliciesOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cdn.aio.CdnManagementClient`'s
:attr:`security_policies` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_profile(
self, resource_group_name: str, profile_name: str, **kwargs: Any
) -> AsyncIterable["_models.SecurityPolicy"]:
"""Lists security policies associated with the profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SecurityPolicy or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicyListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_profile_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_profile.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("SecurityPolicyListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_profile.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies"} # type: ignore
@distributed_trace_async
async def get(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> _models.SecurityPolicy:
"""Gets an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SecurityPolicy or the result of cls(response)
:rtype: ~azure.mgmt.cdn.models.SecurityPolicy
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
request = build_get_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy, (IO, bytes)):
_content = security_policy
else:
_json = self._serialize.body(security_policy, "SecurityPolicy")
request = build_create_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: _models.SecurityPolicy,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Required.
:type security_policy: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy: Union[_models.SecurityPolicy, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Creates a new security policy within the specified profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy: The security policy properties. Is either a model type or a IO type.
Required.
:type security_policy: ~azure.mgmt.cdn.models.SecurityPolicy or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy=security_policy,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
async def _patch_initial(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> _models.SecurityPolicy:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(security_policy_update_properties, (IO, bytes)):
_content = security_policy_update_properties
else:
_json = self._serialize.body(security_policy_update_properties, "SecurityPolicyUpdateParameters")
request = build_patch_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._patch_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_patch_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@overload
async def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: _models.SecurityPolicyUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Required.
:type security_policy_update_properties: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_patch(
self,
resource_group_name: str,
profile_name: str,
security_policy_name: str,
security_policy_update_properties: Union[_models.SecurityPolicyUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.SecurityPolicy]:
"""Updates an existing security policy within a profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:param security_policy_update_properties: Security policy update properties. Is either a model
type or a IO type. Required.
:type security_policy_update_properties: ~azure.mgmt.cdn.models.SecurityPolicyUpdateParameters
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityPolicy or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cdn.models.SecurityPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.SecurityPolicy]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._patch_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
security_policy_update_properties=security_policy_update_properties,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("SecurityPolicy", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_patch.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
async def _delete_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_request(
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.AfdErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
@distributed_trace_async
async def begin_delete(
self, resource_group_name: str, profile_name: str, security_policy_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing security policy within profile.
:param resource_group_name: Name of the Resource group within the Azure subscription. Required.
:type resource_group_name: str
:param profile_name: Name of the Azure Front Door Standard or Azure Front Door Premium profile
which is unique within the resource group. Required.
:type profile_name: str
:param security_policy_name: Name of the security policy under the profile. Required.
:type security_policy_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial( # type: ignore
resource_group_name=resource_group_name,
profile_name=profile_name,
security_policy_name=security_policy_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(
AsyncPollingMethod,
AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs),
) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/securityPolicies/{securityPolicyName}"} # type: ignore
| 0.875548 | 0.077797 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.