pokelance.cache.cache ⚓︎

AbilityCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Ability']

A cache for abilities.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

BaseCache(max_size=100) ⚓︎

Bases: MutableMapping[_KT, _VT]

Base class for all caches.

Parameters:
  • max_size (int, default: 100 ) –

    The maximum size of the cache.

Attributes:
  • _max_size (int) –

    The maximum size of the cache.

  • _cache (Dict[_KT, _VT]) –

    The cache itself.

  • _endpoints (Dict[str, int]) –

    The endpoints that are cached.

  • _endpoints_cached (bool) –

    Whether or not the endpoints are cached.

  • _client (PokeLance) –

    The client that this cache is for.

Examples:

Python Console Session
>>> import asyncio
>>> from pokelance import PokeLance
>>>
>>> async def main():
...     client = PokeLance()
...     print(await client.ping())
...     await asyncio.sleep(5)  # Wait for all the endpoints to load automatically. If not just load them manually.
...     # from pokelance.http import Endpoint
...     # data = await client.http.request(Endpoint.get_berry_endpoints())
...     # client.berry._cache.load_documents(str(client.berry.__class__.__name__).lower(), "berry", data)
...     # print(client.berry.cache.berry.endpoints)
...     # await client.berry.cache.berry.load_all(client.http)
...     print(client.berry.cache.berry)
...     await client.berry.cache.berry.save('temp')  # Save the cache to a file.
...     await client.berry.cache.berry.load('temp')  # Load the cache from a file.
...     print(client.berry.cache.berry)
...     await client.close()
>>>
>>> asyncio.run(main())
Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

cache: t.Dict[_KT, _VT] property ⚓︎

The cache itself.

Returns:
  • Dict[_KT, _VT]

    The cache itself.

endpoints: t.Dict[str, Endpoint] property ⚓︎

The endpoints that are cached.

Returns:
  • Dict[str, Endpoint]

    The endpoints that are cached.

load(path='.') async ⚓︎

Load the cache from a file.

Parameters:
  • path (str, default: '.' ) –

    The path to load the cache from.

Source code in pokelance/cache/cache.py
Python
async def load(self, path: str = ".") -> None:
    """Load the cache from a file.

    Parameters
    ----------
    path: str
        The path to load the cache from.
    """
    async with aiofiles.open(pathlib.Path(f"{path}/{self.__class__.__name__}.json"), "r") as f:
        data = json.loads(await f.read())
    self._max_size = len(data)
    route_model = importlib.import_module("pokelance.http").__dict__["Route"]
    value_type = str(self.__orig_bases__[0].__args__[1]).split(".")[-1]  # type: ignore
    model: "models.BaseModel" = importlib.import_module("pokelance.models").__dict__[value_type]
    for endpoint, info in data.items():
        route = route_model(endpoint=endpoint)
        self.setdefault(route, model.from_payload(info))

load_all() async ⚓︎

Load all documents/data from api into the cache. (Endpoints must be cached first)

Source code in pokelance/cache/cache.py
Python
async def load_all(self) -> None:
    """
    Load all documents/data from api into the cache. (Endpoints must be cached first)
    """
    if not self._endpoints_cached:
        raise RuntimeError("The endpoints have not been cached yet.")
    self._client.logger.info(f"Loading {self.__class__.__name__}...")
    route_model = importlib.import_module("pokelance.http").__dict__["Route"]
    value_type = str(self.__orig_bases__[0].__args__[1]).split(".")[-1]  # type: ignore
    model: "models.BaseModel" = importlib.import_module("pokelance.models").__dict__[value_type]
    self._max_size = len(self._endpoints)
    for endpoint in self._endpoints.values():
        route = route_model(endpoint=f"/{endpoint.url.strip('/').split('/')[-2]}/{str(endpoint)}")
        data = self.get(route, None)
        self.setdefault(route, data if data else model.from_payload(await self._client.http.request(route)))
    self._client.logger.info(f"Loaded {self.__class__.__name__}.")

load_documents(data) ⚓︎

Load documents into the cache.

Parameters:
Source code in pokelance/cache/cache.py
Python
def load_documents(self, data: t.List[t.Dict[str, str]]) -> None:
    """Load documents into the cache.

    Parameters
    ----------
    data: typing.List[typing.Dict[str, str]]
        The data to load.
    """
    for document in data:
        self._endpoints[document["name"]] = Endpoint(url=document["url"], id=int(document["url"].split("/")[-2]))
    self._endpoints_cached = True

save(path='.') async ⚓︎

Save the cache to a file.

Parameters:
  • path (str, default: '.' ) –

    The path to save the cache to.

Source code in pokelance/cache/cache.py
Python
async def save(self, path: str = ".") -> None:
    """Save the cache to a file.

    Parameters
    ----------
    path: str
        The path to save the cache to.
    """
    pathlib.Path(path).mkdir(parents=True, exist_ok=True)
    dummy: t.Dict[str, t.Dict[str, t.Any]] = {k.endpoint: v.raw for k, v in self.items()}
    async with aiofiles.open(pathlib.Path(f"{path}/{self.__class__.__name__}.json"), "w") as f:
        await f.write("{\n")
        for n, (k, v) in enumerate(dummy.items()):
            await f.write("\n".join([4 * " " + i for i in f'"{k}": {json.dumps(v, indent=4)}'.split("\n")]))
            if n != len(dummy) - 1:
                await f.write(",\n")
        await f.write("\n}")

wait_until_ready() async ⚓︎

Wait until the all the endpoints are cached.

Source code in pokelance/cache/cache.py
Python
async def wait_until_ready(self) -> None:
    """Wait until the all the endpoints are cached."""
    await self._client.http.connect()
    while not self._endpoints_cached and self._client.cache_endpoints:
        await asyncio.sleep(0.5)

BerryCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Berry']

A cache for berries.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

BerryFirmnessCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.BerryFirmness']

A cache for berry firmnesses.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

BerryFlavorCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.BerryFlavor']

A cache for berry flavors.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

CharacteristicCache(max_size=100) ⚓︎

Bases: SecondaryTypeCache['Route', 'models.Characteristic']

A cache for characteristics.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

ContestEffectCache(max_size=100) ⚓︎

Bases: SecondaryTypeCache['Route', 'models.ContestEffect']

A cache for contest effects.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

ContestTypeCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.ContestType']

A cache for contest types.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

EggGroupCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.EggGroup']

A cache for egg groups.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

EncounterConditionCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.EncounterCondition']

A cache for encounter conditions.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

EncounterConditionValueCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.EncounterConditionValue']

A cache for encounter condition values.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

EncounterMethodCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.EncounterMethod']

A cache for encounter methods.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

EvolutionChainCache(max_size=100) ⚓︎

Bases: SecondaryTypeCache['Route', 'models.EvolutionChain']

A cache for evolution chains.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

EvolutionTriggerCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.EvolutionTrigger']

A cache for evolution triggers.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

GamesGenerationCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Generation']

A cache for games generations.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

GamesPokedexCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Pokedex']

A cache for games pokedexes.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

GamesVersionCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Version']

A cache for games versions.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

GamesVersionGroupCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.VersionGroup']

A cache for games version groups.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

GenderCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Gender']

A cache for genders.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

GrowthRateCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.GrowthRate']

A cache for growth rates.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

ItemAttributeCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.ItemAttribute']

A cache for item attributes.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

ItemCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Item']

A cache for items.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

ItemCategoryCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.ItemCategory']

A cache for item categories.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

ItemFlingEffectCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.ItemFlingEffect']

A cache for item fling effects.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

ItemPocketCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.ItemPocket']

A cache for item pockets.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

LocationAreaCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.LocationArea']

A cache for location areas.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

LocationCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Location']

A cache for locations.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MachineCache(max_size=100) ⚓︎

Bases: SecondaryTypeCache['Route', 'models.Machine']

A cache for machines.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MoveAilmentCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.MoveAilment']

A cache for move ailments.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MoveBattleStyleCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.MoveBattleStyle']

A cache for move battle styles.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MoveCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Move']

A cache for moves.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MoveCategoryCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.MoveCategory']

A cache for move categories.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MoveDamageClassCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.MoveDamageClass']

A cache for move damage classes.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MoveLearnMethodCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.MoveLearnMethod']

A cache for move learn methods.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

MoveTargetCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.MoveTarget']

A cache for move targets.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

NatureCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Nature']

A cache for natures.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PalParkAreaCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.PalParkArea']

A cache for pal park areas.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokeathlonStatCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.PokeathlonStat']

A cache for pokeathlon stats.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokemonCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Pokemon']

A cache for pokemon.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokemonColorCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.PokemonColor']

A cache for pokemon colors.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokemonFormCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.PokemonForm']

A cache for pokemon forms.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokemonHabitatCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.PokemonHabitats']

A cache for pokemon habitats.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokemonLocationAreaCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.LocationAreaEncounter']

A cache for pokemon location areas.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokemonShapeCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.PokemonShape']

A cache for pokemon shapes.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

PokemonSpeciesCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.PokemonSpecies']

A cache for pokemon species.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

RegionCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Region']

A cache for regions.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

SecondaryTypeCache(max_size=100) ⚓︎

Bases: BaseCache[_KT, _VT]

A cache for secondary types with differing endpoints.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

cache: t.Dict[_KT, _VT] property ⚓︎

The cache itself.

Returns:
  • Dict[_KT, _VT]

    The cache itself.

endpoints: t.Dict[str, Endpoint] property ⚓︎

The endpoints that are cached.

Returns:
  • Dict[str, Endpoint]

    The endpoints that are cached.

load(path='.') async ⚓︎

Load the cache from a file.

Parameters:
  • path (str, default: '.' ) –

    The path to load the cache from.

Source code in pokelance/cache/cache.py
Python
async def load(self, path: str = ".") -> None:
    """Load the cache from a file.

    Parameters
    ----------
    path: str
        The path to load the cache from.
    """
    async with aiofiles.open(pathlib.Path(f"{path}/{self.__class__.__name__}.json"), "r") as f:
        data = json.loads(await f.read())
    self._max_size = len(data)
    route_model = importlib.import_module("pokelance.http").__dict__["Route"]
    value_type = str(self.__orig_bases__[0].__args__[1]).split(".")[-1]  # type: ignore
    model: "models.BaseModel" = importlib.import_module("pokelance.models").__dict__[value_type]
    for endpoint, info in data.items():
        route = route_model(endpoint=endpoint)
        self.setdefault(route, model.from_payload(info))

load_all() async ⚓︎

Load all documents/data from api into the cache. (Endpoints must be cached first)

Source code in pokelance/cache/cache.py
Python
async def load_all(self) -> None:
    """
    Load all documents/data from api into the cache. (Endpoints must be cached first)
    """
    if not self._endpoints_cached:
        raise RuntimeError("The endpoints have not been cached yet.")
    self._client.logger.info(f"Loading {self.__class__.__name__}...")
    route_model = importlib.import_module("pokelance.http").__dict__["Route"]
    value_type = str(self.__orig_bases__[0].__args__[1]).split(".")[-1]  # type: ignore
    model: "models.BaseModel" = importlib.import_module("pokelance.models").__dict__[value_type]
    self._max_size = len(self._endpoints)
    for endpoint in self._endpoints.values():
        route = route_model(endpoint=f"/{endpoint.url.strip('/').split('/')[-2]}/{str(endpoint)}")
        data = self.get(route, None)
        self.setdefault(route, data if data else model.from_payload(await self._client.http.request(route)))
    self._client.logger.info(f"Loaded {self.__class__.__name__}.")

load_documents(data) ⚓︎

Load documents into the cache. Endpoints are different for secondary types.

Parameters:
Source code in pokelance/cache/cache.py
Python
def load_documents(self, data: t.List[t.Dict[str, str]]) -> None:
    """Load documents into the cache. Endpoints are different for secondary types.

    Parameters
    ----------
    data: typing.List[typing.Dict[str, str]]
        The data to load.
    """
    for document in data:
        self._endpoints[document["url"].split("/")[-2]] = Endpoint(
            url=document["url"], id=int(document["url"].split("/")[-2])
        )
    self._endpoints_cached = True

save(path='.') async ⚓︎

Save the cache to a file.

Parameters:
  • path (str, default: '.' ) –

    The path to save the cache to.

Source code in pokelance/cache/cache.py
Python
async def save(self, path: str = ".") -> None:
    """Save the cache to a file.

    Parameters
    ----------
    path: str
        The path to save the cache to.
    """
    pathlib.Path(path).mkdir(parents=True, exist_ok=True)
    dummy: t.Dict[str, t.Dict[str, t.Any]] = {k.endpoint: v.raw for k, v in self.items()}
    async with aiofiles.open(pathlib.Path(f"{path}/{self.__class__.__name__}.json"), "w") as f:
        await f.write("{\n")
        for n, (k, v) in enumerate(dummy.items()):
            await f.write("\n".join([4 * " " + i for i in f'"{k}": {json.dumps(v, indent=4)}'.split("\n")]))
            if n != len(dummy) - 1:
                await f.write(",\n")
        await f.write("\n}")

wait_until_ready() async ⚓︎

Wait until the all the endpoints are cached.

Source code in pokelance/cache/cache.py
Python
async def wait_until_ready(self) -> None:
    """Wait until the all the endpoints are cached."""
    await self._client.http.connect()
    while not self._endpoints_cached and self._client.cache_endpoints:
        await asyncio.sleep(0.5)

StatCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Stat']

A cache for stats.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

SuperContestEffectCache(max_size=100) ⚓︎

Bases: SecondaryTypeCache['Route', 'models.SuperContestEffect']

A cache for super contest effects.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False

TypeCache(max_size=100) ⚓︎

Bases: BaseCache['Route', 'models.Type']

A cache for types.

Source code in pokelance/cache/cache.py
Python
def __init__(self, max_size: int = 100) -> None:
    self._max_size = max_size
    self._cache: t.Dict[_KT, _VT] = {}
    self._endpoints: t.Dict[str, Endpoint] = {}
    self._endpoints_cached: bool = False