Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
aecorn opened this issue Jan 29, 2025 · 0 comments
Open

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

aecorn opened this issue Jan 29, 2025 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@aecorn
Copy link
Collaborator

aecorn commented Jan 29, 2025

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)
@aecorn aecorn added the enhancement New feature or request label Jan 29, 2025
@aecorn aecorn self-assigned this Jan 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant