Microsoft Azure Traffic Manager Management Client Library for Python
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Primary client class for managing all Traffic Manager resources with Azure authentication and subscription-based operations. The client provides access to all Traffic Manager management capabilities through organized operation groups.
Creates a Traffic Manager management client with Azure authentication and subscription context.
class TrafficManagerManagementClient:
"""Main client for Traffic Manager management operations."""
def __init__(
self,
credential: TokenCredential,
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs
):
"""
Initialize Traffic Manager management client.
Args:
credential (TokenCredential): Azure authentication credential
subscription_id (str): Azure subscription ID
base_url (str): Azure Resource Manager endpoint URL
**kwargs: Additional client configuration options
"""
def close(self) -> None:
"""Close the client and release resources."""
def __enter__(self) -> "TrafficManagerManagementClient":
"""Context manager entry."""
def __exit__(self, *exc_details) -> None:
"""Context manager exit with cleanup."""from azure.mgmt.trafficmanager import TrafficManagerManagementClient
from azure.identity import DefaultAzureCredential, ClientSecretCredential, ManagedIdentityCredential
# Basic client with default credential
credential = DefaultAzureCredential()
client = TrafficManagerManagementClient(credential, "your-subscription-id")
# Client with service principal authentication
credential = ClientSecretCredential(
tenant_id="your-tenant-id",
client_id="your-client-id",
client_secret="your-client-secret"
)
client = TrafficManagerManagementClient(credential, "your-subscription-id")
# Client with managed identity (for Azure resources)
credential = ManagedIdentityCredential()
client = TrafficManagerManagementClient(credential, "your-subscription-id")
# Client with custom endpoint (e.g., Azure Government)
client = TrafficManagerManagementClient(
credential,
"your-subscription-id",
base_url="https://management.usgovcloudapi.net"
)
# Context manager usage for automatic cleanup
with TrafficManagerManagementClient(credential, subscription_id) as client:
profiles = list(client.profiles.list_by_subscription())
# Client automatically closed when exiting contextFor asynchronous operations, use the async version of the client.
from azure.mgmt.trafficmanager.aio import TrafficManagerManagementClient
class TrafficManagerManagementClient:
"""Async Traffic Manager management client."""
def __init__(
self,
credential: AsyncTokenCredential,
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs
): ...
async def close(self) -> None:
"""Close the async client and release resources."""
async def __aenter__(self) -> "TrafficManagerManagementClient":
"""Async context manager entry."""
async def __aexit__(self, *exc_details) -> None:
"""Async context manager exit with cleanup."""Async Usage Examples:
import asyncio
from azure.mgmt.trafficmanager.aio import TrafficManagerManagementClient
from azure.identity.aio import DefaultAzureCredential
async def manage_traffic_manager():
credential = DefaultAzureCredential()
async with TrafficManagerManagementClient(credential, subscription_id) as client:
# List all profiles asynchronously
profiles = []
async for profile in client.profiles.list_by_subscription():
profiles.append(profile)
# Create multiple operations concurrently
tasks = []
for i in range(3):
task = client.profiles.get("my-rg", f"profile-{i}")
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
print(f"Error: {result}")
else:
print(f"Profile: {result.name}")
# Run async operations
asyncio.run(manage_traffic_manager())The client provides access to Traffic Manager operations through specialized operation group properties:
class TrafficManagerManagementClient:
"""Client operation groups for Traffic Manager resources."""
# Profile management operations
profiles: ProfilesOperations
# Endpoint management operations
endpoints: EndpointsOperations
# Geographic hierarchy operations
geographic_hierarchies: GeographicHierarchiesOperations
# Heat map and analytics operations
heat_map: HeatMapOperations
# Real user metrics operations
traffic_manager_user_metrics_keys: TrafficManagerUserMetricsKeysOperations# Access different operation groups through the client
client = TrafficManagerManagementClient(credential, subscription_id)
# Profile operations
profiles = list(client.profiles.list_by_subscription())
profile = client.profiles.get("my-rg", "my-profile")
# Endpoint operations
endpoint = client.endpoints.get("my-rg", "my-profile", "AzureEndpoints", "my-endpoint")
# Geographic operations
geo_hierarchy = client.geographic_hierarchies.get_default()
# Analytics operations
heat_map = client.heat_map.get("my-rg", "my-profile")
# User metrics operations
rum_key = client.traffic_manager_user_metrics_keys.create_or_update()from azure.core.pipeline.policies import RetryPolicy
from azure.mgmt.trafficmanager import TrafficManagerManagementClient
# Configure custom retry policy
retry_policy = RetryPolicy(
retry_total=5,
retry_backoff_factor=2.0,
retry_on_status_codes=[408, 429, 500, 502, 503, 504]
)
client = TrafficManagerManagementClient(
credential,
subscription_id,
retry_policy=retry_policy,
timeout=60 # 60 second timeout
)# Add custom headers and user agent
client = TrafficManagerManagementClient(
credential,
subscription_id,
user_agent_policy=UserAgentPolicy("MyApp/1.0"),
headers_policy=HeadersPolicy({"X-Custom-Header": "MyValue"})
)import logging
from azure.mgmt.trafficmanager import TrafficManagerManagementClient
# Enable Azure SDK logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("azure.mgmt.trafficmanager")
logger.setLevel(logging.DEBUG)
# Client will now log HTTP requests and responses
client = TrafficManagerManagementClient(credential, subscription_id)from azure.core.exceptions import (
HttpResponseError,
ResourceNotFoundError,
ClientAuthenticationError,
ResourceExistsError
)
try:
profile = client.profiles.get("my-rg", "nonexistent-profile")
except ResourceNotFoundError as e:
print(f"Profile not found: {e.message}")
except ClientAuthenticationError as e:
print(f"Authentication failed: {e.message}")
except HttpResponseError as e:
print(f"HTTP error {e.status_code}: {e.message}")def safe_traffic_manager_operation():
try:
client = TrafficManagerManagementClient(credential, subscription_id)
# Attempt operation
profile = client.profiles.create_or_update(
"my-rg",
"my-profile",
profile_config
)
return profile
except ClientAuthenticationError:
print("Authentication failed - check credentials")
raise
except ResourceExistsError:
print("Profile already exists - use update instead")
return client.profiles.get("my-rg", "my-profile")
except ResourceNotFoundError:
print("Resource group not found - create it first")
raise
except HttpResponseError as e:
if e.status_code == 429:
print("Rate limited - retry after delay")
time.sleep(60)
return safe_traffic_manager_operation()
else:
print(f"Unexpected HTTP error: {e.status_code} - {e.message}")
raise
except Exception as e:
print(f"Unexpected error: {type(e).__name__} - {e}")
raise
finally:
# Always close client
client.close()from azure.identity import ClientSecretCredential
# Service principal with secret
credential = ClientSecretCredential(
tenant_id="00000000-0000-0000-0000-000000000000",
client_id="11111111-1111-1111-1111-111111111111",
client_secret="your-client-secret"
)
# Service principal with certificate
from azure.identity import CertificateCredential
credential = CertificateCredential(
tenant_id="00000000-0000-0000-0000-000000000000",
client_id="11111111-1111-1111-1111-111111111111",
certificate_path="/path/to/cert.pem"
)from azure.identity import ManagedIdentityCredential
# System-assigned managed identity
credential = ManagedIdentityCredential()
# User-assigned managed identity
credential = ManagedIdentityCredential(
client_id="22222222-2222-2222-2222-222222222222"
)from azure.identity import AzureCliCredential, InteractiveBrowserCredential
# Use Azure CLI credentials (for development)
credential = AzureCliCredential()
# Interactive browser authentication (for development)
credential = InteractiveBrowserCredential(
tenant_id="00000000-0000-0000-0000-000000000000"
)from azure.identity import DefaultAzureCredential, ChainedTokenCredential
# Default credential chain (recommended for production)
credential = DefaultAzureCredential()
# Custom credential chain
credential = ChainedTokenCredential(
ManagedIdentityCredential(), # Try managed identity first
ClientSecretCredential(...), # Then service principal
AzureCliCredential() # Finally CLI credentials
)Install with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-trafficmanager