Skip to content

PokeLance

pokelance.client ⚓︎

PokeLance(*, audio_cache_size=128, image_cache_size=128, cache_size=100, logger=None, file_logging=False, cache_endpoints=True, session=None) ⚓︎

Main class to interact with the PokeAPI.

Attributes:

Name Type Description
_http HttpClient

The HTTP client used to make requests to the PokeAPI.

_logger Union[Logger, Logger]

The logger used to log information about the client.

_ext_tasks List[Tuple[Callable[[], Coroutine[Any, Any, None]], str]]

A list of coroutines to load extension data.

cache_endpoints bool

Whether to cache endpoints. Defaults to True.

EXTENSIONS Path

The path to the extensions directory.

berry Berry

The berry extension.

contest Contest

The contest extension.

encounter Encounter

The encounter extension.

evolution Evolution

The evolution extension.

game Game

The game extension.

item Item

The item extension.

location Location

The location extension.

machine Machine

The machine extension.

move Move

The move extension.

pokemon Pokemon

The pokemon extension.

Examples:

Python Console Session
>>> import pokelance
>>> import asyncio
>>> client = pokelance.PokeLance()
>>> async def main() -> None:
...     print(await client.ping())
...     await client.close()
>>> asyncio.run(main())

Parameters:

Name Type Description Default
audio_cache_size int

The size of the audio cache. Defaults to 128.

128
image_cache_size int

The size of the image cache. Defaults to 128.

128
cache_size int

The size of the cache to use for the HTTP client.

100
logger Optional[Logger]

The logger to use. If not provided, a new logger will be created.

None
file_logging bool

Whether to log to a file. Defaults to False.

False
session Optional[ClientSession]

The session to use for the HTTP client. It is recommended to use the default.

None
Source code in pokelance/client.py
Python
def __init__(
    self,
    *,
    audio_cache_size: int = 128,
    image_cache_size: int = 128,
    cache_size: int = 100,
    logger: t.Optional["logging.Logger"] = None,
    file_logging: bool = False,
    cache_endpoints: bool = True,
    session: t.Optional["aiohttp.ClientSession"] = None,
) -> None:
    """
    Parameters
    ----------
    audio_cache_size : int
        The size of the audio cache. Defaults to 128.
    image_cache_size : int
        The size of the image cache. Defaults to 128.
    cache_size : int
        The size of the cache to use for the HTTP client.
    logger : typing.Optional[logging.Logger]
        The logger to use. If not provided, a new logger will be created.
    file_logging : bool
        Whether to log to a file. Defaults to False.
    session : typing.Optional[aiohttp.ClientSession]
        The session to use for the HTTP client. It is recommended to use the default.
    """
    self._logger = logger or Logger(name="pokelance", file_logging=file_logging)
    self._http = HttpClient(client=self, session=session, cache_size=cache_size)
    self.cache_endpoints = cache_endpoints
    self._ext_tasks: t.List[t.Tuple[t.Callable[[], t.Coroutine[t.Any, t.Any, None]], str]] = []
    self._image_cache_size = image_cache_size
    self._audio_cache_size = audio_cache_size
    self.get_image_async.set_size(image_cache_size)
    self.get_audio_async.set_size(audio_cache_size)
    self.setup_hook()

audio_cache_size: int property writable ⚓︎

The size of the audio cache.

Returns:

Type Description
int

The size of the audio cache.

ext_tasks: t.List[t.Tuple[t.Callable[[], t.Coroutine[t.Any, t.Any, None]], str]] property ⚓︎

A list of coroutines to load extension data.

Returns:

Type Description
List[Tuple[Callable[[], Coroutine[Any, Any, None]], str]]

The list of tasks.

http: HttpClient property ⚓︎

The HTTP client used to make requests to the PokeAPI.

Returns:

Type Description
HttpClient

The HTTP client.

image_cache_size: int property writable ⚓︎

The size of the image cache.

Returns:

Type Description
int

The size of the image cache.

logger: t.Union[logging.Logger, Logger] property ⚓︎

The logger used to log information about the client.

Returns:

Type Description
Logger

The logger.

add_extension(name, extension) ⚓︎

Adds an extension to the client. This is called automatically when an extension is loaded.

Parameters:

Name Type Description Default
name str

The name of the extension.

required
extension BaseExtension

The extension to add.

required
Source code in pokelance/client.py
Python
def add_extension(self, name: str, extension: "BaseExtension") -> None:
    """
    Adds an extension to the client. This is called automatically when an extension is loaded.

    Parameters
    ----------
    name : str
        The name of the extension.
    extension : BaseExtension
        The extension to add.
    """
    self._ext_tasks.append((extension.setup, name))
    setattr(self, name, extension)

close() async ⚓︎

Closes the client session. Recommended to use this when the client is no longer needed. Not needed if the client is used in a context manager.

Source code in pokelance/client.py
Python
async def close(self) -> None:
    """
    Closes the client session. Recommended to use this when the client is no longer needed.
    Not needed if the client is used in a context manager.
    """
    self.logger.warning("Closing session!")
    await self._http.close()

from_url(url) async ⚓︎

Constructs a request from urls present in the data.

Parameters:

Name Type Description Default
url str

The URL to construct the request from.

required

Returns:

Type Description
BaseType

The data from the URL.

Raises:

Type Description
ValueError

If the url is invalid.

ResourceNotFound

If the data is not found.

Source code in pokelance/client.py
Python
async def from_url(self, url: str) -> BaseType:
    """
    Constructs a request from urls present in the data.

    Parameters
    ----------
    url : str
        The URL to construct the request from.

    Returns
    -------
    BaseType
        The data from the URL.

    Raises
    ------
    ValueError
        If the url is invalid.
    ResourceNotFound
        If the data is not found.
    """
    if params := ExtensionEnum.validate_url(url):
        return await self.getch_data(params.extension, params.category, params.value)
    raise ValueError(f"Invalid URL: {url}")

get_audio_async(url) async ⚓︎

Gets an audio from the url asynchronously.

Parameters:

Name Type Description Default
url str

The URL to get the audio from.

required

Returns:

Type Description
bytes

The audio data.

Source code in pokelance/client.py
Python
@alru_cache(maxsize=128, typed=True)
async def get_audio_async(self, url: str) -> bytes:
    """
    Gets an audio from the url asynchronously.

    Parameters
    ----------
    url : str
        The URL to get the audio from.

    Returns
    -------
    bytes
        The audio data.
    """
    return await self._http.load_audio(url)

get_image_async(url) async ⚓︎

Gets an image from the url asynchronously.

Parameters:

Name Type Description Default
url str

The URL to get the image from.

required

Returns:

Type Description
bytes

The image data.

Source code in pokelance/client.py
Python
@alru_cache(maxsize=128, typed=True)
async def get_image_async(self, url: str) -> bytes:
    """
    Gets an image from the url asynchronously.

    Parameters
    ----------
    url : str
        The URL to get the image from.

    Returns
    -------
    bytes
        The image data.
    """
    return await self._http.load_image(url)

getch_data(ext, category, id_) async ⚓︎

A getch method that looks up the cache for the data first then gets it from the API if it is not found.

Parameters:

Name Type Description Default
ext Union[ExtensionEnum, ExtensionsL, str]

The extension to get the data from.

required
category str

The category to get the data from.

required
id_ Union[int, str]

The ID of the data to get.

required

Returns:

Type Description
BaseType

The data.

Raises:

Type Description
ValueError

If the extension or category is invalid.

ResourceNotFound

If the data is not found.

Examples:

Python Console Session
>>> import pokelance
>>> import asyncio
>>> from pokelance.constants import ExtensionEnum
>>> from pokelance.models import Pokemon
>>> client = pokelance.PokeLance()
>>> async def main() -> None:
...     pokemon: Pokemon = await client.getch_data(ExtensionEnum.Pokemon, "pokemon", 1)
...     print(pokemon.name)
...     await client.close()
>>> asyncio.run(main())
bulbasaur
Source code in pokelance/client.py
Python
async def getch_data(
    self, ext: t.Union[ExtensionEnum, ExtensionsL, str], category: str, id_: t.Union[int, str]
) -> BaseType:
    """
    A getch method that looks up the cache for the data first then gets it from the API if it is not found.

    Parameters
    ----------
    ext : Union[ExtensionEnum, ExtensionsL, str]
        The extension to get the data from.
    category : str
        The category to get the data from.
    id_ : Union[int, str]
        The ID of the data to get.

    Returns
    -------
    BaseType
        The data.

    Raises
    ------
    ValueError
        If the extension or category is invalid.
    ResourceNotFound
        If the data is not found.

    Examples
    --------
    >>> import pokelance
    >>> import asyncio
    >>> from pokelance.constants import ExtensionEnum
    >>> from pokelance.models import Pokemon
    >>> client = pokelance.PokeLance()
    >>> async def main() -> None:
    ...     pokemon: Pokemon = await client.getch_data(ExtensionEnum.Pokemon, "pokemon", 1)
    ...     print(pokemon.name)
    ...     await client.close()
    >>> asyncio.run(main())
    bulbasaur
    """
    if isinstance(ext, str) and (ext := str(ext).title()) not in ExtensionEnum.__members__:
        raise ValueError(f"Invalid extension: {ext}")
    categories = ExtensionEnum.get_categories(ext) if isinstance(ext, str) else ext.categories  # type: ignore
    if (category := category.lower().replace("_", "-")) not in categories:
        raise ValueError(f"Invalid category: {category}, valid categories: {categories}")
    category = category.replace("-", "_")
    ext_ = getattr(self, ext.lower()) if isinstance(ext, str) else getattr(self, ext.name.lower())
    get_, fetch_ = getattr(ext_, f"get_{category}"), getattr(ext_, f"fetch_{category}")
    return t.cast(BaseType, get_(id_) or await fetch_(id_))

ping() async ⚓︎

Pings the PokeAPI and returns the latency.

Returns:

Type Description
float

The latency of the PokeAPI.

Source code in pokelance/client.py
Python
async def ping(self) -> float:
    """
    Pings the PokeAPI and returns the latency.

    Returns
    -------
    float
        The latency of the PokeAPI.
    """
    return await self._http.ping()

setup_hook() ⚓︎

The setup hook to be called after the client is created. This is called automatically when the client is created. It is not recommended to call this manually.

Source code in pokelance/client.py
Python
def setup_hook(self) -> None:
    """
    The setup hook to be called after the client is created.
    This is called automatically when the client is created.
    It is not recommended to call this manually.
    """
    self._logger.info(f"Using cache size: {self._http.cache.max_size}")
    for extension in self.EXTENSIONS.iterdir():
        if extension.is_file() and extension.suffix == ".py":
            if "_" not in extension.stem:
                module = __import__(f"pokelance.ext.{extension.stem}", fromlist=["setup"])
                module.setup(self)
    self._logger.info("Setup complete")

wait_until_ready() async ⚓︎

Waits until the http client caches all the endpoints.

Source code in pokelance/client.py
Python
async def wait_until_ready(self) -> None:
    """
    Waits until the http client caches all the endpoints.
    """
    await self._http.connect()
    self.logger.info("Waiting until ready...")
    while self._http._tasks_queue and self.cache_endpoints:
        await asyncio.sleep(0.5)
    self.logger.info("Ready!")