initial commit
This commit is contained in:
44
src/anilistapi/api.py
Normal file
44
src/anilistapi/api.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import requests
|
||||
from .schemas.manga import Manga
|
||||
from .queries.manga import MANGA_QUERY, MANGA_ID_QUERY
|
||||
from limit import limit
|
||||
from anilistapi import __version__, __contact__
|
||||
import os
|
||||
|
||||
REQUEST_LIMIT = 1
|
||||
REQUEST_PERIOD = 2
|
||||
|
||||
|
||||
class AnilistAPI:
|
||||
def __init__(self):
|
||||
# add system information to the user agent
|
||||
self.userAgent = f"AnilistAPI/{__version__} {os.uname().sysname}/{os.uname().machine} Python/{os.uname().release} - {__contact__}"
|
||||
pass
|
||||
|
||||
@limit(REQUEST_LIMIT, REQUEST_PERIOD)
|
||||
def request(self, query: str, variables: dict) -> dict:
|
||||
url = "https://graphql.anilist.co"
|
||||
response = requests.post(url, json={"query": query, "variables": variables})
|
||||
if response.status_code != 200:
|
||||
return {}
|
||||
# raise Exception(f"Error: {response}, response: {response.json()}, query: {query}, variables: {variables}")
|
||||
return response.json()
|
||||
|
||||
def search_manga(self, search: str) -> list[Manga]:
|
||||
variables = {"search": search}
|
||||
response = self.request(MANGA_QUERY, variables)
|
||||
# check if reponse has data Page and media
|
||||
if not response.get("data", {}).get("Page", {}).get("media"):
|
||||
return []
|
||||
res = []
|
||||
for manga in response["data"]["Page"]["media"]:
|
||||
res.append(Manga(**manga))
|
||||
return res
|
||||
|
||||
def get_manga(self, id: int) -> Manga:
|
||||
assert isinstance(id, int), "id must be an integer"
|
||||
variables = {"id": id}
|
||||
response = self.request(MANGA_ID_QUERY, variables)
|
||||
if not response.get("data", {}).get("Media"):
|
||||
return None
|
||||
return Manga(**response["data"]["Media"])
|
||||
Reference in New Issue
Block a user