Skip to content

Caching

Tip

TLDR: Simply use the default caching for most projects:

from nexar.cache import DEFAULT_CACHE_CONFIG
from nexar.client import NexarClient

client = NexarClient(
    riot_api_key="your_api_key",
    cache_config=DEFAULT_CACHE_CONFIG,
)

Caching is "smart" by using varying TTLs (time-to-live) for each endpoint:

Endpoint Cache Duration
Matches Forever
Accounts/Summoners 24 hours
League Entries 5 minutes
Match IDs 1 minute

All other requests use the default expiration time (1 hour).

Use CacheConfig to specify a default cache time, pick a storage backend, and configure the cache location.

Quick Start

By default, caching uses a 1-hour TTL and stores responses to a SQLite file in ~/.nexar/:

import asyncio

from nexar.client import NexarClient
from nexar.enums import Region

client = NexarClient(
    riot_api_key="your_api_key",
    default_region=Region.NA1,
)


async def main() -> None:
    async with client:
        # First call hits the API
        player = await client.get_player(riot_id="bexli#bex")

        # Second call uses cached data
        player = await client.get_player(riot_id="bexli#bex")


if __name__ == "__main__":
    asyncio.run(main())

Cache Backends

Two cache backends are supported, both of which respect the smart TTL overrides:

  • SQLite (default): Persistent cache stored in a file. Best for long-running applications and CLI tools.
  • Memory: Ephemeral in-memory cache. Best for one-off scripts, tests, and environments without write access.

Configure the backend using CacheConfig:

import asyncio
import os
from nexar.client import NexarClient
from nexar.cache import CacheConfig
from nexar.enums import Region


async def main() -> None:
    api_key = os.environ.get("RIOT_API_KEY")
    if not api_key:
        print("Please set RIOT_API_KEY environment variable.")
        return

    # 1. Custom SQLite Configuration
    # Useful for separating dev/prod caches or specific tool caches
    sqlite_config = CacheConfig(
        backend="sqlite",
        cache_name="my_custom_cache",  # Creates my_custom_cache.sqlite
        expire_after=3600,  # 1 hour default expiration
    )

    print("--- Using Custom SQLite Backend ---")
    async with NexarClient(riot_api_key=api_key, cache_config=sqlite_config) as client:
        # Note: Using get_player which returns a Player object with both account and summoner data
        player = await client.get_player(riot_id="Agurin#EUW", region=Region.EUW1)
        print(f"Got player (SQLite): {player.game_name}#{player.tag_line}")

    # 2. Memory Configuration
    # Useful for tests, scripts, or read-only environments (Lambda/Cloud Run)
    memory_config = CacheConfig(
        backend="memory",
        expire_after=600,  # 10 minutes default
    )

    print("\n--- Using Memory Backend ---")
    async with NexarClient(riot_api_key=api_key, cache_config=memory_config) as client:
        player = await client.get_player(riot_id="Agurin#EUW", region=Region.EUW1)
        print(f"Got player (Memory): {player.game_name}#{player.tag_line}")


if __name__ == "__main__":
    asyncio.run(main())

SQLite Cache Location

The SQLite backend creates nexar_cache.sqlite in ~/.nexar/ by default. The name and location can be customized:

config = CacheConfig(
    backend="sqlite",
    cache_name="my_app_cache",  # Creates my_app_cache.sqlite
    cache_dir="/tmp/cache"      # Saves to /tmp/cache/my_app_cache.sqlite
)

Custom Cache Configuration

Create custom configurations for specific expiration times:

from nexar.cache import CacheConfig

# SQLite cache with custom settings
custom_config = CacheConfig(
    backend="sqlite",
    expire_after=7200,  # 2 hours
)

# Memory cache with custom expiration
memory_config = CacheConfig(
    backend="memory",
    expire_after=900,  # 15 minutes
)

Predefined Configurations

DEFAULT_CACHE_CONFIG

Uses the SQLite backend with a 1-hour default TTL. The smart endpoint overrides (Matches, Accounts, etc.) are active by default.

NO_CACHE_CONFIG

Disables caching entirely, every request hits the API.

Cache Management

Manage the cache and view statistics through the client:

async with NexarClient(riot_api_key="your_api_key") as client:
    # Get cache information (size, backend, count)
    info = await client.get_cache_info()

    # Clear all cached data
    await client.clear_cache()

    # View API call statistics (hits, fresh calls, rate)
    stats = client.get_api_call_stats()
    client.print_api_call_summary()

Manual Refresh

Models like Player provide a refresh_cache() method to clear their internal state and force fresh API calls on the next access.

Best Practices

  1. Use the default cache for most applications. The SQLite backend with its smart endpoint-specific TTLs is optimized for Riot's API.
  2. Use the SQLite backend when you want data to persist between runs. This speeds up API calls and saves rate limits.
  3. Use the Memory backend for scripts where persistence isn't needed or where file system access is restricted.
  4. Disable caching only when you need real-time data for every request. Use NO_CACHE_CONFIG sparingly.