1. import requests
  2. import json
  3. import time
  4. def flatten_http_response(url, timeout=10):
  5. """
  6. Flattens the structure of an HTTP response for development purposes.
  7. Includes a timeout to prevent indefinite waiting.
  8. """
  9. try:
  10. response = requests.get(url, timeout=timeout)
  11. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  12. # Attempt to parse the response as JSON
  13. try:
  14. data = response.json()
  15. except json.JSONDecodeError:
  16. data = response.text # if not JSON, use text
  17. # Flatten the structure recursively
  18. def flatten(obj, prefix=""):
  19. flattened = {}
  20. if isinstance(obj, dict):
  21. for k, v in obj.items():
  22. new_prefix = prefix + k + "_" if prefix else k + "_"
  23. flattened.update(flatten(v, new_prefix))
  24. elif isinstance(obj, list):
  25. for i, v in enumerate(obj):
  26. new_prefix = prefix + str(i) + "_"
  27. flattened.update(flatten(v, new_prefix))
  28. else:
  29. flattened[prefix[:-1]] = obj # remove trailing underscore
  30. return flattened
  31. flattened_data = flatten(data)
  32. return flattened_data
  33. except requests.exceptions.RequestException as e:
  34. print(f"Request error: {e}")
  35. return None
  36. except Exception as e:
  37. print(f"An unexpected error occurred: {e}")
  38. return None
  39. if __name__ == '__main__':
  40. # Example usage
  41. url = "https://httpbin.org/json" # A test URL that returns JSON
  42. flattened_response = flatten_http_response(url)
  43. if flattened_response:
  44. print(json.dumps(flattened_response, indent=4))

Add your comment