Universal Analytics Python 3 Client
This library provides a Python 3 interface to Google Analytics, supporting the Universal Analytics Measurement Protocol, with an interface loosely modeled after Google's analytics.js. It's a fork of `universal-analytics-python` with added support for Python 3, batch requests, and both synchronous and asynchronous API calls. The current version is 1.1.1, released on April 28, 2021. However, please note that Universal Analytics (UA) has ceased processing new data as of July 1, 2023, and all UA services and APIs, including the ones this library interacts with, will be fully shut down on July 1, 2024.
Common errors
-
ModuleNotFoundError: No module named 'universal_analytics_python3'
cause Incorrect import path. The top-level package for import is `universal_analytics`, not the PyPI package name.fixChange your import statements from `from universal_analytics_python3 import ...` to `from universal_analytics import ...` -
RuntimeWarning: coroutine 'AsyncHTTPRequest.close' was never awaited
cause In versions 1.1.1 and later, `AsyncHTTPRequest.close()` was renamed to `aclose()` and must be awaited, or the client should be used within an `async with` block. This warning indicates the asynchronous close method was not correctly called.fixIf manually closing, change `http_request_instance.close()` to `await http_request_instance.aclose()`. The recommended approach is to use `async with AsyncHTTPRequest() as http:` which handles closing automatically. -
Command ignored. Unknown target: undefined.
cause This error, originating from the underlying Universal Analytics JavaScript library or Measurement Protocol, indicates that the tracker was not correctly initialized or attempts were made to send data before a valid tracker was established, often related to an invalid tracking ID or `cookieDomain` setting.fixEnsure the Google Analytics Tracking ID ('UA-XXXXX-Y') is correct and that the `Tracker` is properly instantiated before calling `send()`. For web contexts, verify `cookieDomain` settings or try with `cookieDomain='auto'` for testing.
Warnings
- breaking Google's Universal Analytics (UA) has been deprecated. It ceased processing new data on July 1, 2023, and all UA services and APIs, including the ones this library relies on, will be completely shut down on July 1, 2024. This library is effectively abandoned for practical use cases involving current data.
- breaking For asynchronous usage with `httpx` (used by `AsyncHTTPRequest`), version 1.1.1 changed the client closing behavior to use `aclose()` instead of `close()` to align with `httpx` best practices. Older code calling `close()` on `AsyncHTTPRequest` instances will likely fail or lead to resource leaks.
- gotcha Attempts to sum 'Users' metric data across different time granularities (e.g., aggregating daily user counts to monthly) in Universal Analytics reports (and thus via this API) will lead to inflated and incorrect results due to the non-additive nature of the 'Users' metric.
Install
-
pip install universal-analytics-python3
Imports
- Tracker
from universal_analytics_python3 import Tracker
from universal_analytics import Tracker
- HTTPRequest
from universal_analytics import HTTPRequest
- HTTPBatchRequest
from universal_analytics import HTTPBatchRequest
- AsyncHTTPRequest
from universal_analytics import AsyncHTTPRequest
- AsyncHTTPBatchRequest
from universal_analytics import AsyncHTTPBatchRequest
Quickstart
import asyncio
from universal_analytics import Tracker, AsyncHTTPRequest
# NOTE: Universal Analytics has been deprecated by Google.
# This code will NOT send new data to Google Analytics after July 1, 2023,
# and the Universal Analytics API will be completely shut down on July 1, 2024.
# Please migrate to Google Analytics 4 (GA4) and use the appropriate GA4 client library.
# This example is for demonstration purposes only for the 'universal-analytics-python3' library.
GA_TRACKING_ID = 'UA-XXXXX-Y' # Replace with your Universal Analytics Tracking ID
CLIENT_ID = 'unique-user-id-123'
async def main():
print("Attempting to send Universal Analytics hit (note: UA is deprecated).")
async with AsyncHTTPRequest() as http:
tracker = Tracker(GA_TRACKING_ID, http, client_id=CLIENT_ID)
await tracker.send('pageview', path='/home', title='Homepage')
print(f"Sent pageview hit for client {CLIENT_ID} to {GA_TRACKING_ID}")
if __name__ == '__main__':
# Only run if a tracking ID is somewhat plausible
if GA_TRACKING_ID.startswith('UA-'):
asyncio.run(main())
else:
print("Invalid GA_TRACKING_ID format. Please set a valid 'UA-XXXXX-Y' for demonstration.")