question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Cost Management] [API Management] Azure Cost Management Package just throws first 1000 lines and not managing the paging from the cost management rest api

See original GitHub issue
  • Package Name: azure-mgmt-costmanagement
  • Package Version: 3.0.0
  • Operating System: Windows
  • Python Version: 3.9.6

Describe the bug When you call the Usage method in python: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py that is related to this REST api endpoint here https://docs.microsoft.com/es-es/rest/api/cost-management/query/usage the python api is not looping to get next page using the nextLink attribute in the response described here https://docs.microsoft.com/es-es/rest/api/cost-management/query/usage#queryresult so we get a 1000 rows maximum per execution and no way to manage the paging with this library

To Reproduce

from azure.mgmt.costmanagement        import CostManagementClient
from azure.mgmt.costmanagement.models import QueryAggregation,QueryGrouping,QueryDataset,QueryDefinition,QueryTimePeriod,QueryFilter,QueryComparisonExpression
from azure.mgmt.resource              import ResourceManagementClient
from azure.identity                   import DefaultAzureCredential
from IPython.display                  import display, HTML
from typing                           import ContextManager

import json
import pandas as pd
import datetime as dt
import calendar
import numpy as np


thedate = dt.datetime.combine(dt.date.today(), dt.time())
first = thedate.replace(day=1)
last = thedate.replace(day = calendar.monthrange(thedate.year, thedate.month)[1])

credential = DefaultAzureCredential()
subscription_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

scope = '/subscriptions/{}'.format(subscription_id)

client = ResourceManagementClient(credential, subscription_id)

cmgmtc = CostManagementClient(credential = credential)

"""
'ResourceGroup','ResourceGroupName','ResourceLocation',
'ConsumedService','ResourceType','ResourceId',
'MeterId','BillingMonth','MeterCategory',
'MeterSubcategory','Meter','AccountName',
'DepartmentName','SubscriptionId','SubscriptionName',
'ServiceName','ServiceTier','EnrollmentAccountName',
'BillingAccountId','ResourceGuid','BillingPeriod',
'InvoiceNumber','ChargeType','PublisherType',
'ReservationId','ReservationName','Frequency',
'PartNumber','CostAllocationRuleName','MarkupRuleName',
'PricingModel','BenefitId','BenefitName',''
"""


query_template = ( 
  QueryDefinition( 
     type      = "ActualCost"
    , timeframe = "ThisMonth" 
   , dataset   = 
     QueryDataset(
        granularity  = "Monthly"
      , aggregation  = { 
        "totalCost": QueryAggregation(name = "Cost", function = "Sum")
        ,"totalCostUSD": QueryAggregation(name = "CostUSD", function = "Sum") 
        }
      , grouping     = [
             QueryGrouping(name = "ResourceGroupName", type = "Dimension")
            ,QueryGrouping(name = "ResourceId"       , type = "Dimension")
            ,QueryGrouping(name = "ResourceType"     , type = "Dimension")
        ]
      , filter =  
        QueryFilter(
          dimensions = 
            QueryComparisonExpression(
                name = "ResourceGroupName"
              , operator = "In"
              , values = ["RESOURCE_GROUP"]
            )
        )
     )
  )
)



replaced_query = (
  query_template.deserialize(
    json.loads(
      json.dumps(
        query_template.serialize()
      ).replace('RESOURCE_GROUP','destination_rg')
    )
  )
)

result = cmgmtc.query.usage( scope = scope, parameters = replaced_query)

data = pd.DataFrame(result.rows, columns = list(map(lambda col: col.name, result.columns)))
 
data_sorted = data.sort_values(by='CostUSD' ,ascending = False)

data_filtered = data_sorted

pd.set_option('display.max_rows', data_filtered.shape[0]+1)

display(HTML(data_filtered.to_html())) 

Expected behavior As a python developer using this package I would expect the result to be an iterable so I can get all result pages not just the first one

Screenshots If applicable, add screenshots to help explain your problem.

Additional context Add any other context about the problem here.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
victorsalesacommented, Jun 9, 2022

@sgiovetti I was the one notificating that and copying that. It seems that the python api is generated with azurerest tool. I guess that it will be simply changing the swagger definition for the next release to include the iteration capability but no answer yet

1reaction
omrodrigcommented, Apr 1, 2022

Sorry for the inconvenience. but we have a backlog item to fix this issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cost Management] [API Management] Azure Cost ... - GitHub
Cost Management ] [API Management] Azure Cost Management Package just throws first 1000 lines and not managing the paging from the cost management...
Read more >
API Management pricing - Microsoft Azure
Get detailed pricing info for the Azure API Management cloud service. No upfront ... Prices are estimates only and are not intended as...
Read more >
Manage tables | BigQuery - Google Cloud
This document describes how to manage tables in BigQuery. You can manage your BigQuery tables in the following ways: Update table properties:.
Read more >
Available system properties - ServiceNow Docs
To learn more about the cookies we use and how you can change your preferences, please read our Cookie Policy and visit our...
Read more >
Building an ASP.NET Web API with ASP.NET Core - Toptal
NET Developer Damir Imangulov shows how to build a robust RESTful API using ASP. ... I'll show you how to make an API...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found