Skip to content

CacheManager

pokelance.cache.cache_manager ⚓︎

Base ⚓︎

Base class for all caches.

Attributes:

Name Type Description
max_size int

The maximum cache size.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

BaseCache(max_size=100) ⚓︎

Bases: MutableMapping[_KT, _VT]

Base class for all caches.

Parameters:

Name Type Description Default
max_size int

The maximum size of the cache.

100

Attributes:

Name Type Description
_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:

Type Description
Dict[_KT, _VT]

The cache itself.

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

The endpoints that are cached.

Returns:

Type Description
Dict[str, Endpoint]

The endpoints that are cached.

load(path='.') async ⚓︎

Load the cache from a file.

Parameters:

Name Type Description Default
path str

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:

Name Type Description Default
data List[Dict[str, str]]

The data to load.

required
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:

Name Type Description Default
path str

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)

Berry ⚓︎

Bases: Base

Cache for berry related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

berry BerryCache

The berry.

berry_firmness BerryFirmnessCache

The berry firmness.

berry_flavor BerryFlavorCache

The berry flavor.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Cache ⚓︎

Cache for all endpoints.

Attributes:

Name Type Description
client PokeLance

The pokelance client.

max_size int

The maximum cache size.

berry Berry

The berry cache.

contest Contest

The contest cache.

encounter Encounter

The encounter cache.

evolution Evolution

The evolution cache.

game Game

The game cache.

item Item

The item cache.

location Location

The location cache.

machine Machine

The machine cache.

move Move

The move cache.

pokemon Pokemon

The pokemon cache.

load_documents(category, _type, data) ⚓︎

Loads the endpoint data into the cache.

Parameters:

Name Type Description Default
category str

The category of the endpoint.

required
_type str

The type of the endpoint.

required
data List[Dict[str, str]]

The data to load.

required
Source code in pokelance/cache/cache_manager.py
Python
def load_documents(self, category: str, _type: str, data: t.List[t.Dict[str, str]]) -> None:
    """Loads the endpoint data into the cache.

    Parameters
    ----------
    category: str
        The category of the endpoint.
    _type: str
        The type of the endpoint.
    data: typing.List[Dict[str, str]]
        The data to load.
    """
    getattr(getattr(self, category.lower()), _type).load_documents(data)

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[Base]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, Base) and obj.default is not None:
            obj.default.set_size(max_size)

Contest ⚓︎

Bases: Base

Cache for contest related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

contest_type ContestTypeCache

The contest type.

contest_effect ContestEffectCache

The contest effect.

super_contest_effect SuperContestEffectCache

The super contest effect.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Encounter ⚓︎

Bases: Base

Cache for encounter related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

encounter_method EncounterMethodCache

The method in which the encounter happens.

encounter_condition EncounterConditionCache

The condition in which the encounter happens.

encounter_condition_value EncounterConditionValueCache

The condition value in which the encounter happens.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Evolution ⚓︎

Bases: Base

Cache for evolution related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

evolution_chain EvolutionChainCache

The evolution chain of a Pokemon.

evolution_trigger EvolutionTriggerCache

The trigger in which the evolution happens.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Game ⚓︎

Bases: Base

Cache for game related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

generation GamesGenerationCache

The generation of a game.

pokedex GamesPokedexCache

The pokedex of a game.

version GamesVersionCache

The version of a game.

version_group GamesVersionGroupCache

The version group of a game.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Item ⚓︎

Bases: Base

Cache for item related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

item ItemCache

The item.

item_attribute ItemAttributeCache

The attribute of an item.

item_category ItemCategoryCache

The category of an item.

item_fling_effect ItemFlingEffectCache

The fling effect of an item.

item_pocket ItemPocketCache

The pocket of an item.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Location ⚓︎

Bases: Base

Cache for location related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

location LocationCache

The location.

location_area LocationAreaCache

The location area.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Machine ⚓︎

Bases: Base

Cache for machine related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

machine MachineCache

The machine that teaches a move.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Move ⚓︎

Bases: Base

Cache for move related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

move MoveCache

The move.

move_ailment MoveAilmentCache

The ailment of a move.

move_battle_style MoveBattleStyleCache

The battle style of a move.

move_category MoveCategoryCache

The category of a move.

move_damage_class MoveDamageClassCache

The damage class of a move.

move_learn_method MoveLearnMethodCache

The learn method of a move.

move_target MoveTargetCache

The target of a move.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size

Pokemon ⚓︎

Bases: Base

Cache for pokemon related endpoints.

Attributes:

Name Type Description
max_size int

The maximum cache size.

ability AbilityCache

The ability.

characteristic CharacteristicCache

The characteristic.

egg_group EggGroupCache

The egg group.

gender GenderCache

The gender cache.

growth_rate GrowthRateCache

The growth rate.

nature NatureCache

The nature.

pokeathlon_stat PokeathlonStatCache

The pokeathlon stat.

pokemon PokemonCache

The pokemon.

pokemon_color PokemonColorCache

The color of a pokemon.

pokemon_form PokemonFormCache

The form of a pokemon.

pokemon_habitat PokemonHabitatCache

The habitat of a pokemon.

pokemon_shape PokemonShapeCache

The shape of a pokemon.

pokemon_species PokemonSpeciesCache

The species of a pokemon.

stat StatCache

The stat.

type TypeCache

The type.

set_client(client) ⚓︎

Set the client for the cache.

Parameters:

Name Type Description Default
client PokeLance

The client to set.

required
Source code in pokelance/cache/cache_manager.py
Python
def set_client(self, client: "PokeLance") -> None:
    """Set the client for the cache.

    Parameters
    ----------
    client: pokelance.PokeLance
        The client to set.
    """
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._client = client

set_size(max_size=100) ⚓︎

Set the maximum cache size.

Parameters:

Name Type Description Default
max_size int

The maximum cache size.

100
Source code in pokelance/cache/cache_manager.py
Python
def set_size(self, max_size: int = 100) -> None:
    """Set the maximum cache size.

    Parameters
    ----------
    max_size: int
        The maximum cache size.
    """
    self.max_size = max_size
    obj: attrs.Attribute[BaseCache[t.Any, t.Any]]
    for obj in self.__attrs_attrs__:
        if isinstance(obj.default, BaseCache) and obj.default is not None:
            obj.default._max_size = max_size