Microsoft Azure Cost Management Client Library for Python providing comprehensive access to cost analysis, billing data, budgets, alerts, exports, and recommendations.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Download pricing information and rate cards for Azure services through price sheet operations. These operations provide access to current and historical pricing data for billing accounts with Microsoft Partner Agreement or Microsoft Customer Agreement.
Download the price sheet for a specific invoice, providing detailed pricing information for all services used during that billing period.
def begin_download(
billing_account_name: str,
billing_profile_name: str,
invoice_name: str
) -> LROPoller[DownloadURL]:
"""
Gets a URL to download the pricesheet for an invoice.
Args:
billing_account_name (str): The ID that uniquely identifies a billing account
billing_profile_name (str): The ID that uniquely identifies a billing profile
invoice_name (str): The ID that uniquely identifies an invoice
Returns:
LROPoller[DownloadURL]: Long-running operation poller for price sheet download
Note:
Supported for billing accounts with Microsoft Partner Agreement or Microsoft Customer Agreement.
"""Download the current month's price sheet for a billing profile, providing up-to-date pricing information for all available Azure services.
def begin_download_by_billing_profile(
billing_account_name: str,
billing_profile_name: str
) -> LROPoller[DownloadURL]:
"""
Gets a URL to download the current month's pricesheet for a billing profile.
Args:
billing_account_name (str): The ID that uniquely identifies a billing account
billing_profile_name (str): The ID that uniquely identifies a billing profile
Returns:
LROPoller[DownloadURL]: Long-running operation poller for price sheet download
Note:
Supported for billing accounts with Microsoft Partner Agreement or Microsoft Customer Agreement.
Due to Azure product growth, download may be a Zip file containing multiple CSV files.
"""from azure.identity import DefaultAzureCredential
from azure.mgmt.costmanagement import CostManagementClient
# Initialize client
credential = DefaultAzureCredential()
client = CostManagementClient(credential)
# Define billing identifiers
billing_account_name = "12345678-1234-1234-1234-123456789012:12345678-1234-1234-1234-123456789012_2019-05-31"
billing_profile_name = "BP123456-5678-9012-3456-789012345678"
invoice_name = "INV-2024-01-123456"
# Start price sheet download
print(f"Starting price sheet download for invoice {invoice_name}")
operation = client.price_sheet.begin_download(
billing_account_name=billing_account_name,
billing_profile_name=billing_profile_name,
invoice_name=invoice_name
)
print("Price sheet download initiated...")
print(f"Operation status: {operation.status()}")
# Wait for completion
result = operation.result()
print(f"Download completed. URL expires at: {result.expiry_time}")
print(f"Download URL: {result.download_url}")import time
from datetime import datetime, timedelta
# Download current month's price sheet
print("Starting current month price sheet download...")
current_operation = client.price_sheet.begin_download_by_billing_profile(
billing_account_name=billing_account_name,
billing_profile_name=billing_profile_name
)
print("Current month price sheet download initiated...")
# Monitor progress
while not current_operation.done():
print("Price sheet generation in progress...")
time.sleep(30) # Wait 30 seconds
current_result = current_operation.result()
print(f"Current month price sheet ready")
print(f"Valid until: {current_result.valid_till}")
print(f"Download URL: {current_result.download_url}")
# Download and process price sheet
if current_result.download_url:
print("Price sheet is ready for download")
print(f"URL will expire at: {current_result.expiry_time}")
# Calculate time remaining
if current_result.expiry_time:
time_remaining = current_result.expiry_time - datetime.utcnow()
print(f"Time remaining to download: {time_remaining}")import concurrent.futures
from typing import Dict, List
def download_price_sheets_for_invoices(invoice_names: List[str]) -> Dict[str, str]:
"""Download price sheets for multiple invoices concurrently"""
def download_single_invoice(invoice_name: str) -> tuple[str, str]:
operation = client.price_sheet.begin_download(
billing_account_name=billing_account_name,
billing_profile_name=billing_profile_name,
invoice_name=invoice_name
)
result = operation.result()
return invoice_name, result.download_url
# Download price sheets concurrently
download_urls = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
future_to_invoice = {
executor.submit(download_single_invoice, invoice): invoice
for invoice in invoice_names
}
for future in concurrent.futures.as_completed(future_to_invoice):
invoice_name = future_to_invoice[future]
try:
invoice_name, download_url = future.result()
download_urls[invoice_name] = download_url
print(f"Price sheet ready for {invoice_name}")
except Exception as exc:
print(f"Invoice {invoice_name} generated an exception: {exc}")
return download_urls
# Download price sheets for multiple invoices
invoice_list = ["INV-2024-01-123456", "INV-2024-02-234567", "INV-2024-03-345678"]
price_sheet_urls = download_price_sheets_for_invoices(invoice_list)
for invoice, url in price_sheet_urls.items():
print(f"{invoice}: {url}")from azure.core.exceptions import HttpResponseError
import time
def download_price_sheet_with_retry(max_retries: int = 3):
"""Download price sheet with retry logic for robustness"""
for attempt in range(max_retries):
try:
print(f"Attempt {attempt + 1} to download price sheet...")
operation = client.price_sheet.begin_download_by_billing_profile(
billing_account_name=billing_account_name,
billing_profile_name=billing_profile_name
)
# Wait for completion with timeout
start_time = time.time()
timeout = 300 # 5 minutes
while not operation.done():
if time.time() - start_time > timeout:
raise TimeoutError("Price sheet download timed out")
time.sleep(10)
result = operation.result()
print("Price sheet download successful!")
return result
except HttpResponseError as e:
print(f"HTTP error on attempt {attempt + 1}: {e.status_code} - {e.message}")
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt) # Exponential backoff
except TimeoutError as e:
print(f"Timeout on attempt {attempt + 1}: {e}")
if attempt == max_retries - 1:
raise
time.sleep(30)
except Exception as e:
print(f"Unexpected error on attempt {attempt + 1}: {e}")
if attempt == max_retries - 1:
raise
time.sleep(10)
# Use retry logic
try:
price_sheet_result = download_price_sheet_with_retry()
print(f"Final download URL: {price_sheet_result.download_url}")
except Exception as e:
print(f"Failed to download price sheet after retries: {e}")class DownloadURL:
"""
The URL to download the generated price sheet.
Attributes:
expiry_time (datetime): The time at which report URL becomes invalid/expires in UTC
valid_till (datetime): The time at which report URL becomes invalid/expires in UTC
download_url (str): The URL to download the generated price sheet
"""
expiry_time: datetime
valid_till: datetime
download_url: strPrice sheet operations provide essential functionality for accessing Azure pricing data, supporting both invoice-specific and current pricing information downloads. The operations use long-running operation patterns to handle potentially large price sheet files and support concurrent downloads for multiple billing periods.
Install with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-costmanagement