Skip to content

Refactor package to allow multiple async requests against the API #124

@aecorn

Description

@aecorn

Description

The join_all variants and correspndence methods are now VERY slow. Some of this could probably be elevated by postponing the api-requests from the init of the classes, and building up from the get_json-function as async / await. Finally doing a asyncio.gather() on all the "fetch" methods on the postponed API-calls from the class inits.

async def get_json(url: str, params: dict) -> Any:
    """Asynchronously fetch JSON data from the KLASS API.

    Args:
        url (str): The API URL.
        params (dict): Query parameters.

    Returns:
        Any: JSON response.
    """
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=config.HEADERS, params=params) as response:
            response.raise_for_status()
            return await response.json()

The functions calling get_json, need to be async and await get_json and so on.

When you want to fire off multiple requests at once, you may want to do a .gather():

async def fetch_all_variants(variants: list[KlassVariant]):
    """Fetch API data for multiple KlassVariant instances concurrently."""
    tasks = [variant.fetch() for variant in variants]
    await asyncio.gather(*tasks)

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions