Matomo API

Apps

class integreat_cms.matomo_api.apps.MatomoApiConfig(app_name, app_module)[source]

Bases: AppConfig

MatomoApiClient config inheriting the django AppConfig

__init__(app_name, app_module)[source]
classmethod create(entry)[source]

Factory that creates an app config from an entry in INSTALLED_APPS.

default_auto_field[source]
get_model(model_name, require_ready=True)[source]

Return the model with the given case-insensitive model_name.

Raise LookupError if no model exists with this name.

get_models(include_auto_created=False, include_swapped=False)[source]

Return an iterable of models.

By default, the following models aren’t included:

  • auto-created models for many-to-many relations without an explicit intermediate table,

  • models that have been swapped out.

Set the corresponding keyword argument to True to include such models. Keyword arguments aren’t documented; they’re a private API.

import_models()[source]
name: Final[str] = 'integreat_cms.matomo_api'[source]

Full Python path to the application

ready()[source]

Override this method in subclasses to run code when Django starts.

verbose_name: Final[Promise] = 'Matomo API'[source]

Human-readable name for the application

Matomo API Client

class integreat_cms.matomo_api.matomo_api_client.MatomoApiClient(region: Region)[source]

Bases: object

This class helps to interact with Matomo API. There are three functions which can be used publicly:

Parameters:

region (Region)

__init__(region: Region) None[source]

Constructor initializes the class variables

Parameters:

region (Region) – The region this Matomo API Manager connects to

Return type:

None

async async_fetch(session: ClientSession, **kwargs: Any) dict[str, Any] | list[int][source]

Uses aiohttp.ClientSession.get() to perform an asynchronous GET request to the Matomo API.

Parameters:
  • session (ClientSession) – The session object which is used for the request

  • **kwargs (Any) – The parameters which are passed to the Matomo API

Raises:

MatomoException – When a ClientError was raised during a Matomo API request

Returns:

The parsed json result

Return type:

dict[str, Any] | list[int]

fetch(**kwargs: Any) dict[str, Any][source]

Uses request.post() to perform an synchronous GET request to the Matomo API.

Parameters:
  • session – The session object which is used for the request

  • **kwargs (Any) – The parameters which are passed to the Matomo API

Raises:

MatomoException – When a ClientError was raised during a Matomo API request

Returns:

The parsed json result

Return type:

dict[str, Any]

static get_access_data(total_visits: dict, webapp_downloads: dict, offline_downloads: dict) tuple[list[dict], list[str]][source]

Structure the datasets for accesses in a chart.js-compatible format, returning it and the custom legend entries

Parameters:
  • total_visits (dict) – The total amount of visits

  • webapp_downloads (dict) – The amount of visits via the WebApp

  • offline_downloads (dict) – The amount of offline downloads

Returns:

The chart.js-datasets and custom legend entries

Return type:

tuple[list[dict], list[str]]

static get_language_data(languages: list[Language], datasets: list[dict]) tuple[list[dict], list[str]][source]

Structure the datasets for languages in a chart.js-compatible format, returning it and the custom legend entries

Parameters:
  • languages (list[Language]) – The list of languages

  • datasets (list[dict]) – The Matomo datasets

Returns:

The chart.js-datasets and custom legend entries

Return type:

tuple[list[dict], list[str]]

get_matomo_id(token_auth: str) int[source]

Returns the matomo website id based on the provided authentication key.

Parameters:

token_auth (str) – The Matomo authentication token which should be used

Raises:

MatomoException – When a ClientError was raised during a Matomo API request or the access token is not correct

Returns:

ID of the connected Matomo instance

Return type:

int

async get_matomo_id_async(**query_params: Any) list[int][source]

Async wrapper to fetch the Matomo ID with aiohttp. Opens a ClientSession and calls async_fetch(). Called from get_matomo_id().

Parameters:

**query_params (Any) – The parameters which are passed to the Matomo API

Returns:

The parsed json result

Raises:

MatomoException – When a ClientError was raised during a Matomo API request

Return type:

list[int]

get_page_accesses(start_date: date, end_date: date, region_slug: str, languages: list[Language], pages: list[Page], prefetched_translations: list[PageTranslation]) None[source]

This function handles getting the page based accesses from Matomo and saving them to the database

Parameters:
  • start_date (date) – Start date

  • end_date (date) – End date

  • region_slug (str) – The region for which we want our page based accesses

  • languages (list[Language]) – List with the active languages of the region

  • pages (list[Page]) – List with prefetch pages of the region

  • prefetched_translations (list[PageTranslation]) – List with prefetched page translations

Return type:

None

get_total_visits(start_date: date, end_date: date, period: str = 'day') dict[str, Any][source]

Returns the total calls within a time range for all languages.

Parameters:
  • start_date (date) – Start date

  • end_date (date) – End date

  • period (str) – The period (one of CHOICES - defaults to DAY)

Raises:

MatomoException – When a ClientError was raised during a Matomo API request

Returns:

The total visits in the ChartData format expected by ChartJs

Return type:

dict[str, Any]

async get_total_visits_async(query_params: dict[str, str | int | None]) dict[str, Any][source]

Async wrapper to fetch the total visits with aiohttp. Opens a ClientSession and calls async_fetch(). Called from get_total_visits().

Parameters:

query_params (dict[str, str | int | None]) – The parameters which are passed to the Matomo API

Raises:

MatomoException – When a ClientError was raised during a Matomo API request

Returns:

The parsed json result

Return type:

dict[str, Any]

get_visits_per_language(start_date: date, end_date: date, period: str) dict[str, Any][source]

Returns the total unique visitors in a timerange as defined in period

Parameters:
  • start_date (date) – Start date

  • end_date (date) – End date

  • period (str) – The period (one of CHOICES)

Returns:

The visits per language in the ChartData format expected by ChartJs

Raises:

MatomoException – When a ClientError was raised during a Matomo API request

Return type:

dict[str, Any]

async get_visits_per_language_async(loop: AbstractEventLoop, query_params: dict[str, Any], languages: list[Language]) list[dict[str, Any]][source]

Async wrapper to fetch the total visits with aiohttp. Opens a ClientSession, creates a Task for each language to call async_fetch() and waits for all tasks to finish with gather(). The returned list of gathered results has the correct order in which the tasks were created (at first the ordered list of languages and the last element is the task for the total visits). Called from get_visits_per_language().

Parameters:
  • loop (AbstractEventLoop) – The asyncio event loop

  • query_params (dict[str, Any]) – The parameters which are passed to the Matomo API

  • languages (list[Language]) – The list of languages which should be retrieved

Raises:

MatomoException – When a ClientError was raised during a Matomo API request

Returns:

The list of gathered results

Return type:

list[dict[str, Any]]

languages: list[Language] = [][source]

The active languages

matomo_id: int | None = None[source]

Matomo ID

matomo_token: str | None = None[source]

Matomo API-key

static simplify_date_labels(date_labels: KeysView[str], period: str) list[Promise][source]

Convert the dates returned by Matomo to more readable labels

Parameters:
  • date_labels (KeysView[str]) – The date labels returned by Matomo

  • period (str) – The period of the labels (determines the format)

Returns:

The readable labels

Return type:

list[Promise]

exception integreat_cms.matomo_api.matomo_api_client.MatomoException[source]

Bases: Exception

Custom Exception class for errors during interaction with Matomo

__init__(*args, **kwargs)[source]
add_note()[source]

Exception.add_note(note) – add a note to the exception

args[source]
with_traceback()[source]

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Utils

integreat_cms.matomo_api.utils.build_infix_recursively(absolute_url: str, language_slug: str, current_page_translation: PageTranslation, translations_lookup: dict[tuple[Any, str], PageTranslation]) str[source]

Build infix of the absolute url of a PageTranslation object from the prefetched PageTranslations recursively. This is a workaround to avoid calling the cache, which is needed when page accesses are fetched with celery.

Parameters:
  • absolut_url – absolute url build at hte point of calling

  • language_slug (str) – Language slug of the current page translation

  • current_page_translation (PageTranslation) – Page translation for that we want the parent slug of

  • prefetched_translations – List with prefetched page translations we select from

  • absolute_url (str)

  • translations_lookup (dict[tuple[Any, str], PageTranslation])

Returns:

A string containing the url build until the point of calling. At the end of the recursion it returns the absolute url of the page translation from the first call

Return type:

str

integreat_cms.matomo_api.utils.get_translation_slug(region_slug: str, prefetched_translations: list[PageTranslation]) dict[int, dict[str, str]][source]

Produce mapping of page ids and language slugs to the absolute url of the corresponding translation. In detail, we need to construct a slug in the foreign language, for example /en/lebensmittel-und-einkaufen needs to become /en/groceries-and-shopping.

Parameters:
  • region_slug (str) – Slug of the region we want the absolute url of

  • prefetched_translations (list[PageTranslation]) – List of prefetched Pagetranslations that we want the absolute urls of

Returns:

A dictionary of page ids, language slugs and the absolute url of the corresponding translation.

Return type:

dict[int, dict[str, str]]