newfetch.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. from msal import ConfidentialClientApplication
  2. import requests
  3. import csv
  4. from typing import List, Dict, Any, Union
  5. # Define your Azure AD and API configurations
  6. TENANT_ID = '82360567-02b6-4a45451f-a4z6-910a811b8131'
  7. CLIENT_ID = 'a3d88cc7-8889-42356548-bd3b-f5689372f07084'
  8. CLIENT_SECRET = 'ibh8Q~LVSzZeeewdeWF546456UHNSoUBP.lz8GBmenXGJTlnbdU'
  9. SCOPE = ['api://a3d88cc7-0789-4238-bd3hb-456456f89667372f07084/.default']
  10. # Define API endpoint configurations
  11. data_endpoint_config = {
  12. 'projects': {
  13. 'fields': 'projects?select=id,name,route,imeis,subline,ws10Icon,routeSecondLayer',
  14. 'order': '&order=name.asc&limit=10',
  15. },
  16. 'latestDeviceData': {
  17. 'fields': 'devices',
  18. 'order': '&order=name.desc',
  19. },
  20. 'data': {
  21. 'fields': 'data?select=id,version,imei,timestamp,network,data,project,location,latest',
  22. 'order': '&order=timestamp.desc&limit=25',
  23. },
  24. }
  25. # Function to retrieve access token using MSAL
  26. def get_access_token(tenant_id: str, client_id: str, client_secret: str, scope: List[str]) -> Union[str, None]:
  27. authority = f"https://login.microsoftonline.com/{tenant_id}"
  28. app = ConfidentialClientApplication(
  29. client_id,
  30. authority=authority,
  31. client_credential=client_secret,
  32. )
  33. result = app.acquire_token_for_client(scopes=scope)
  34. if 'access_token' in result:
  35. return result['access_token']
  36. else:
  37. print('Failed to retrieve access token:', result.get('error_description', 'Unknown error'))
  38. return None
  39. # Function to call API with access token
  40. def call_api_data(access_token: str, query: str) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
  41. headers = {
  42. 'Authorization': f'Bearer {access_token}',
  43. 'Content-Type': 'application/json',
  44. }
  45. url = f"https://api.vodafone.dev/iot-db/{query}"
  46. print(f"Requesting URL: {url}") # Debug: Print URL
  47. print(f"Request Headers: {headers}") # Debug: Print headers
  48. try:
  49. response = requests.get(url, headers=headers)
  50. response.raise_for_status() # Raise an error for bad status codes
  51. return response.json()
  52. except requests.exceptions.HTTPError as http_err:
  53. print(f"HTTP error occurred: {http_err}")
  54. print("Response content:", response.text) # Print full response content
  55. except Exception as err:
  56. print(f"Other error occurred: {err}")
  57. return {} # Return empty dictionary if request fails
  58. # Function to get device data
  59. def get_device_data(query_name: str) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
  60. try:
  61. access_token = get_access_token(TENANT_ID, CLIENT_ID, CLIENT_SECRET, SCOPE)
  62. if access_token:
  63. query_config = data_endpoint_config.get(query_name, {})
  64. query_fields = query_config.get('fields', '')
  65. query_order = query_config.get('order', '')
  66. query = f"{query_fields}{query_order}" # Combine fields and order
  67. if query:
  68. return call_api_data(access_token, query)
  69. else:
  70. print(f'No query found for query name: {query_name}')
  71. else:
  72. print('Failed to retrieve access token.')
  73. except Exception as e:
  74. print(f'Error retrieving data: {str(e)}')
  75. return []
  76. # Function to convert data to CSV
  77. def write_data_to_csv(data: List[Dict[str, Any]], filename: str):
  78. if not data:
  79. print("No data to write to CSV.")
  80. return
  81. # Extract header from the first data item keys
  82. headers = data[0].keys()
  83. try:
  84. with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
  85. writer = csv.DictWriter(csvfile, fieldnames=headers)
  86. writer.writeheader()
  87. writer.writerows(data)
  88. print(f"Data successfully written to {filename}")
  89. except Exception as e:
  90. print(f"Error writing to CSV: {e}")
  91. # Fetch latest device data and write to CSV
  92. if __name__ == '__main__':
  93. query_name = 'data' # Example query name (replace with actual query name)
  94. device_data = get_device_data(query_name)
  95. # Check if device_data is in the expected format
  96. if isinstance(device_data, dict):
  97. # If data is returned as a dictionary, try to get the list of items
  98. device_data = device_data.get('items', [])
  99. # Convert to CSV
  100. write_data_to_csv(device_data, 'device_data.csv')