1. import json
  2. from urllib.parse import urlparse
  3. def aggregate_session_cookies(cookie_strings):
  4. """
  5. Aggregates session cookies from a list of cookie strings and performs basic sanity checks.
  6. """
  7. aggregated_cookies = {}
  8. invalid_cookies = []
  9. for cookie_string in cookie_strings:
  10. try:
  11. cookie = dict(item.split(';') for item in cookie_string.split(',')) # Parse cookie string
  12. # Remove whitespace around key-value pairs
  13. cookie = {k.strip(): v.strip() for k, v in cookie.items()}
  14. aggregated_cookies.update(cookie) # Add to the aggregated dictionary
  15. except Exception as e:
  16. invalid_cookies.append(f"Invalid cookie: {cookie_string} - {str(e)}") # Log invalid cookies
  17. # Sanity checks
  18. if not aggregated_cookies:
  19. print("No valid cookies found.")
  20. return None
  21. # Check for empty cookie values
  22. empty_value_count = sum(1 for value in aggregated_cookies.values() if not value)
  23. if empty_value_count > 0:
  24. print(f"Warning: {empty_value_count} cookies have empty values.")
  25. # Check for cookie name length
  26. long_name_count = sum(1 for name in aggregated_cookies if len(name) > 64)
  27. if long_name_count > 0:
  28. print(f"Warning: {long_name_count} cookie names are longer than 64 characters.")
  29. return aggregated_cookies
  30. if __name__ == '__main__':
  31. # Example usage:
  32. cookie_strings = [
  33. "sessionid=12345; username=testuser; "
  34. "other_param=value; expired=true",
  35. "sessionid=67890; "
  36. "another_param=another_value",
  37. "invalid_cookie" # Example of an invalid cookie string
  38. ]
  39. aggregated_cookies = aggregate_session_cookies(cookie_strings)
  40. if aggregated_cookies:
  41. print(json.dumps(aggregated_cookies, indent=2))

Add your comment