Skip to content

Clients

Nyaa

Nyaa(base_url: str = 'https://nyaa.si/', cache: bool = True, **kwargs: Any)

Nyaa client.

Parameters:

Name Type Description Default
base_url str

The base URL of Nyaa. Default is https://nyaa.si/. This is used for constructing the full URL from relative URLs.

'https://nyaa.si/'
cache bool

Whether to enable caching. Default is True. This will cache the page upon it's first request and then use the cached result for any subsequent requests for the same page. This helps in avoiding HTTP 429 Error but do note some fields like seeders, leechers, and completed are constantly changing and thus caching would mean you won't get the latest data on said fields.

True
kwargs Any

Keyword arguments to pass to the underlying httpx.Client used to make the GET request.

{}
Source code in src/pynyaa/_clients/_sync.py
def __init__(self, base_url: str = "https://nyaa.si/", cache: bool = True, **kwargs: Any) -> None:
    """
    Nyaa client.

    Parameters
    ----------
    base_url : str, optional
        The base URL of Nyaa. Default is `https://nyaa.si/`.
        This is used for constructing the full URL from relative URLs.
    cache : bool, optional
        Whether to enable caching. Default is `True`.
        This will cache the page upon it's first request and then use the cached result
        for any subsequent requests for the same page.
        This helps in avoiding [HTTP 429 Error](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) but
        do note some fields like seeders, leechers, and completed are constantly changing and thus caching would
        mean you won't get the latest data on said fields.
    kwargs : Any, optional
        Keyword arguments to pass to the underlying [`httpx.Client`](https://www.python-httpx.org/api/#client)
        used to make the GET request.
    """
    self._base_url = base_url
    self._cache = cache
    self._kwargs = kwargs
    self._extensions = {"force_cache": self._cache, "cache_disabled": not self._cache}
    self._storage = FileStorage(base_path=get_user_cache_path())

base_url property

base_url: str

This is the base URL, used for constructing the full URL from relative URLs.

cache_path property

cache_path: Path

Path where cache files are stored.

get

get(page: int | str) -> NyaaTorrentPage

Retrieve information from a Nyaa torrent page.

Parameters:

Name Type Description Default
page int or str

The torrent page. This can either be a URL like https://nyaa.si/view/123456 or just the ID like 123456

required

Raises:

Type Description
HTTPStatusError

Nyaa returned a non 2xx response.

Returns:

Type Description
NyaaTorrentPage

A NyaaTorrentPage object representing the retrieved data.

Source code in src/pynyaa/_clients/_sync.py
def get(self, page: int | str) -> NyaaTorrentPage:
    """
    Retrieve information from a Nyaa torrent page.

    Parameters
    ----------
    page : int or str
        The torrent page.
        This can either be a URL like `https://nyaa.si/view/123456`
        or just the ID like `123456`

    Raises
    ------
    HTTPStatusError
        Nyaa returned a non 2xx response.

    Returns
    -------
    NyaaTorrentPage
        A NyaaTorrentPage object representing the retrieved data.
    """

    if isinstance(page, int):
        url = urljoin(self._base_url, f"/view/{page}")
        nyaaid = page
    else:
        url = page
        nyaaid = page.split("/")[-1]  # type: ignore

    with CacheClient(storage=self._storage, **self._kwargs) as client:
        nyaa = client.get(url, extensions=self._extensions).raise_for_status()
        parsed = parse_nyaa_torrent_page(self._base_url, nyaa.text)

        # Get the torrent file and convert it to a torf.Torrent object
        torrent_file = client.get(parsed["torrent_file"], extensions=self._extensions).raise_for_status().content
        torrent = Torrent.read_stream(BytesIO(torrent_file))

        return NyaaTorrentPage(id=nyaaid, url=url, torrent=torrent, **parsed)  # type: ignore

search

search(query: str, *, category: Category | None = None, filter: Filter | None = None) -> Generator[NyaaTorrentPage]

Search for torrents on Nyaa.

Parameters:

Name Type Description Default
query str

The search query string.

required
category Category

The category to filter the search. If None, searches all categories.

None
filter Filter

The filter to apply to the search results. If None, no filter is applied.

None

Raises:

Type Description
HTTPStatusError

Nyaa returned a non 2xx response.

Yields:

Type Description
NyaaTorrentPage

A NyaaTorrentPage object representing the retrieved data.

Source code in src/pynyaa/_clients/_sync.py
def search(
    self,
    query: str,
    *,
    category: Category | None = None,
    filter: Filter | None = None,
) -> Generator[NyaaTorrentPage]:
    """
    Search for torrents on Nyaa.

    Parameters
    ----------
    query : str
        The search query string.
    category : Category, optional
        The category to filter the search. If None, searches all categories.
    filter : Filter, optional
        The filter to apply to the search results. If None, no filter is applied.

    Raises
    ------
    HTTPStatusError
        Nyaa returned a non 2xx response.

    Yields
    -------
    NyaaTorrentPage
        A NyaaTorrentPage object representing the retrieved data.
    """
    with CacheClient(storage=self._storage, **self._kwargs) as client:
        params = dict(
            page="rss",
            f=filter if filter is not None else 0,
            c=category.id if category is not None else "0_0",
            q=query,
        )

        nyaa = client.get(self._base_url, params=params, extensions=self._extensions).raise_for_status()  # type: ignore
        results = parse_nyaa_rss_page(nyaa.text)

        for link in results:
            yield self.get(link)

AsyncNyaa

AsyncNyaa(base_url: str = 'https://nyaa.si/', cache: bool = True, **kwargs: Any)

Async Nyaa client.

Parameters:

Name Type Description Default
base_url str

The base URL of Nyaa. Default is https://nyaa.si/. This is used for constructing the full URL from relative URLs.

'https://nyaa.si/'
cache bool

Whether to enable caching. Default is True. This will cache the page upon it's first request and then use the cached result for any subsequent requests for the same page. This helps in avoiding HTTP 429 Error but do note some fields like seeders, leechers, and completed are constantly changing and thus caching would mean you won't get the latest data on said fields.

True
kwargs Any

Keyword arguments to pass to the underlying httpx.AsyncClient used to make the GET request.

{}
Source code in src/pynyaa/_clients/_async.py
def __init__(self, base_url: str = "https://nyaa.si/", cache: bool = True, **kwargs: Any) -> None:
    """
    Async Nyaa client.

    Parameters
    ----------
    base_url : str, optional
        The base URL of Nyaa. Default is `https://nyaa.si/`.
        This is used for constructing the full URL from relative URLs.
    cache : bool, optional
        Whether to enable caching. Default is `True`.
        This will cache the page upon it's first request and then use the cached result
        for any subsequent requests for the same page.
        This helps in avoiding [HTTP 429 Error](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) but
        do note some fields like seeders, leechers, and completed are constantly changing and thus caching would
        mean you won't get the latest data on said fields.
    kwargs : Any, optional
        Keyword arguments to pass to the underlying [`httpx.AsyncClient`](https://www.python-httpx.org/api/#asyncclient)
        used to make the GET request.
    """
    self._base_url = base_url
    self._cache = cache
    self._kwargs = kwargs
    self._extensions = {"force_cache": self._cache, "cache_disabled": not self._cache}
    self._storage = AsyncFileStorage(base_path=get_user_cache_path())

base_url property

base_url: str

This is the base URL, used for constructing the full URL from relative URLs.

cache_path property

cache_path: Path

Path where cache files are stored.

get async

get(page: int | str) -> NyaaTorrentPage

Retrieve information from a Nyaa torrent page.

Parameters:

Name Type Description Default
page int or str

The torrent page. This can either be a URL like https://nyaa.si/view/123456 or just the ID like 123456

required

Raises:

Type Description
HTTPStatusError

Nyaa returned a non 2xx response.

Returns:

Type Description
NyaaTorrentPage

A NyaaTorrentPage object representing the retrieved data.

Source code in src/pynyaa/_clients/_async.py
async def get(self, page: int | str) -> NyaaTorrentPage:
    """
    Retrieve information from a Nyaa torrent page.

    Parameters
    ----------
    page : int or str
        The torrent page.
        This can either be a URL like `https://nyaa.si/view/123456`
        or just the ID like `123456`

    Raises
    ------
    HTTPStatusError
        Nyaa returned a non 2xx response.

    Returns
    -------
    NyaaTorrentPage
        A NyaaTorrentPage object representing the retrieved data.
    """

    if isinstance(page, int):
        url = urljoin(self._base_url, f"/view/{page}")
        nyaaid = page
    else:
        url = page
        nyaaid = page.split("/")[-1]  # type: ignore

    async with AsyncCacheClient(storage=self._storage, **self._kwargs) as client:
        nyaa = await client.get(url, extensions=self._extensions)
        nyaa.raise_for_status()

        parsed = parse_nyaa_torrent_page(self._base_url, nyaa.text)

        # Get the torrent file and convert it to a torf.Torrent object
        response = await client.get(parsed["torrent_file"], extensions=self._extensions)
        response.raise_for_status()
        torrent = Torrent.read_stream(BytesIO(response.content))

        return NyaaTorrentPage(id=nyaaid, url=url, torrent=torrent, **parsed)  # type: ignore

search async

search(query: str, *, category: Category | None = None, filter: Filter | None = None) -> AsyncGenerator[NyaaTorrentPage]

Search for torrents on Nyaa.

Parameters:

Name Type Description Default
query str

The search query string.

required
category Category

The category to filter the search. If None, searches all categories.

None
filter Filter

The filter to apply to the search results. If None, no filter is applied.

None

Raises:

Type Description
HTTPStatusError

Nyaa returned a non 2xx response.

Yields:

Type Description
NyaaTorrentPage

A NyaaTorrentPage object representing the retrieved data.

Source code in src/pynyaa/_clients/_async.py
async def search(
    self,
    query: str,
    *,
    category: Category | None = None,
    filter: Filter | None = None,
) -> AsyncGenerator[NyaaTorrentPage]:
    """
    Search for torrents on Nyaa.

    Parameters
    ----------
    query : str
        The search query string.
    category : Category, optional
        The category to filter the search. If None, searches all categories.
    filter : Filter, optional
        The filter to apply to the search results. If None, no filter is applied.

    Raises
    ------
    HTTPStatusError
        Nyaa returned a non 2xx response.

    Yields
    -------
    NyaaTorrentPage
        A NyaaTorrentPage object representing the retrieved data.
    """
    async with AsyncCacheClient(storage=self._storage, **self._kwargs) as client:
        params = dict(
            page="rss",
            f=filter if filter is not None else 0,
            c=category.id if category is not None else "0_0",
            q=query,
        )

        nyaa = await client.get(self._base_url, params=params, extensions=self._extensions)  # type: ignore
        nyaa.raise_for_status()
        results = parse_nyaa_rss_page(nyaa.text)

        for link in results:
            yield await self.get(link)