Skip to content

Commit

Permalink
Update Client to use a context manager and update examples to use it.
Browse files Browse the repository at this point in the history
  • Loading branch information
AbstractUmbra committed Apr 14, 2023
1 parent 2ba95fe commit c604846
Show file tree
Hide file tree
Showing 10 changed files with 225 additions and 234 deletions.
55 changes: 27 additions & 28 deletions examples/create_manga.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,46 +9,45 @@
if TYPE_CHECKING:
from hondana.types_.common import LocalizedString

# Create your client, auth is needed for this.
client = hondana.Client(client_id="...", client_secret="...")


async def main():
"""
Here we will create a Manga in MangaDex.
The process is multi-stage, so I will attempt to outline them here.
"""
# Let's login and request OAuth2 details. Currently this will open a webbrowser for the callback.
await client.login()

# Outline the needed attributes for this manga here
manga_title: LocalizedString = {"en": "Some neat manga!", "ja": "本棚"}
original_language = "en"
status = hondana.MangaStatus.ongoing
content_rating = hondana.ContentRating.safe

# Create the manga with them:
draft_manga = await client.create_manga(
title=manga_title, original_language=original_language, status=status, content_rating=content_rating
)
# Using the context manager will try and login if credentials are set, or act anonymously if not.
# Authentication *is* needed for this example.
async with hondana.Client(client_id="...", client_secret="...") as client:
# Outline the needed attributes for this manga here
manga_title: LocalizedString = {"en": "Some neat manga!", "ja": "本棚"}
original_language = "en"
status = hondana.MangaStatus.ongoing
content_rating = hondana.ContentRating.safe

# This manga is now created in "draft" state. This is outlined more here:
# https://api.mangadex.org/docs.html#section/Manga-Creation
# tl;dr it's to remove the spam creations and to ensure there's a cover on the manga... so let's do that now.
with open("our_cover.png", "rb") as file:
cover = file.read()
# Create the manga with them:
draft_manga = await client.create_manga(
title=manga_title, original_language=original_language, status=status, content_rating=content_rating
)

# When we upload a cover, we need to attribute it to a manga, so lets use the draft one we created.
uploaded_cover = await draft_manga.upload_cover(cover=cover, volume=None, description="My awesome cover", locale="en")
print(uploaded_cover)
# This manga is now created in "draft" state. This is outlined more here:
# https://api.mangadex.org/docs.html#section/Manga-Creation
# tl;dr it's to remove the spam creations and to ensure there's a cover on the manga... so let's do that now.
with open("our_cover.png", "rb") as file:
cover = file.read()

# Now that our manga is covered and uploaded, let's submit it for approval with a version of 1:
submitted_manga = await draft_manga.submit_draft(version=1)
print(submitted_manga)
# When we upload a cover, we need to attribute it to a manga, so lets use the draft one we created.
uploaded_cover = await draft_manga.upload_cover(
cover=cover, volume=None, description="My awesome cover", locale="en"
)
print(uploaded_cover)

# NOTE: Something to note is that the version of draft MUST match the version of submitted manga during the approval stage.
# Now that our manga is covered and uploaded, let's submit it for approval with a version of 1:
submitted_manga = await draft_manga.submit_draft(version=1)
print(submitted_manga)

await client.close()
# NOTE: Something to note is that the version of draft MUST match the version of submitted manga during the approval stage.


# we don't log out as exiting the context manager provides a clean exit.
asyncio.run(main())
26 changes: 12 additions & 14 deletions examples/download_manga.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,19 @@
import hondana


client = hondana.Client()


async def main():
# Get the manga, we will need its chapters
manga = await client.get_manga("some-manga-id-here")

# Load the feed of the manga, that contains all chapters.
# To note... I would filter by language here, else you'll potentially have random translations downloaded.
feed = await manga.feed(limit=500, offset=0, translated_language=["en"])

# This is how you recursively download the chapters.
# The string in the `.download()` call is the path to save all the chapters in. It will recursively create it, if needed.
for chapter in feed.chapters:
await chapter.download(f"{manga.title}/{chapter.chapter}")
async with hondana.Client() as client:
# Get the manga, we will need its chapters
manga = await client.get_manga("some-manga-id-here")

# Load the feed of the manga, that contains all chapters.
# To note... I would filter by language here, else you'll potentially have random translations downloaded.
feed = await manga.feed(limit=500, offset=0, translated_language=["en"])

# This is how you recursively download the chapters.
# The string in the `.download()` call is the path to save all the chapters in. It will recursively create it, if needed.
for chapter in feed.chapters:
await chapter.download(f"{manga.title}/{chapter.chapter}")


asyncio.run(main())
33 changes: 13 additions & 20 deletions examples/my_feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,31 +9,24 @@

# We need to log in with username/email and password since MangaDex does not let you create user based API tokens.
# We instead use our credentials to log in and fetch an expiring auth token.
client = hondana.Client(client_id="...", client_secret="...")


async def main() -> hondana.ChapterFeed:
# Let's login first.
await client.login()
async def main() -> None:
async with hondana.Client(client_id="...", client_secret="...") as client:
# Let's get the last 15 minutes of released manga
fifteen_minutes_ago = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(minutes=15)

# Let's get the last 15 minutes of released manga
fifteen_minutes_ago = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(minutes=15)
# And let's order the responses by created at descending
# we also coerce the type here to prevent typechecker issues. This isn't needed but if you use a typechecker this is good to do.
order = FeedOrderQuery(created_at=Order.descending)

# And let's order the responses by created at descending
# we also coerce the type here to prevent typechecker issues. This isn't needed but if you use a typechecker this is good to do.
order = FeedOrderQuery(created_at=Order.descending)
# `feed` will return a ChapterFeed instance. This just has the response info and list of chapters.
feed = await client.get_my_feed(
limit=20, offset=0, translated_language=["en"], created_at_since=fifteen_minutes_ago, order=order
)

# `feed` will return a ChapterFeed instance. This just has the response info and list of chapters.
feed = await client.get_my_feed(
limit=20, offset=0, translated_language=["en"], created_at_since=fifteen_minutes_ago, order=order
)

# Let's view the responses.
print(feed)

await client.close()

return feed
# Let's view the responses.
print(feed)


asyncio.run(main())
22 changes: 9 additions & 13 deletions examples/search_manga.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@
import hondana


client = hondana.Client()


async def search_for_tags() -> hondana.MangaCollection:
async def search_for_tags(client: hondana.Client) -> hondana.MangaCollection:
# Using the tag builder for ease during a query
# This will add a restriction to search for a manga with all 3 of these tags using logical AND
tags = hondana.QueryTags("action", "comedy", "isekai", mode="AND")
Expand All @@ -23,7 +20,7 @@ async def search_for_tags() -> hondana.MangaCollection:
return manga_response


async def more_refined_search() -> hondana.MangaCollection:
async def more_refined_search(client: hondana.Client) -> hondana.MangaCollection:
# let's do a more refined search using many of the query parameters...
tags = hondana.QueryTags("action", "comedy", "isekai", mode="AND")

Expand All @@ -49,15 +46,14 @@ async def more_refined_search() -> hondana.MangaCollection:
return search


async def main():
manga = await search_for_tags()
print(manga)

other_manga = await more_refined_search()
# this search was empty for me at the time of writing, but the fact you get a response at all means it worked.
print(other_manga)
async def main() -> None:
async with hondana.Client() as client:
manga = await search_for_tags(client)
print(manga)

await client.close()
other_manga = await more_refined_search(client)
# this search was empty for me at the time of writing, but the fact you get a response at all means it worked.
print(other_manga)


asyncio.run(main())
35 changes: 15 additions & 20 deletions examples/submitting_a_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,24 @@


# We need to log in as reports cannot be submitted anonymously.
client = hondana.Client(client_id="...", client_secret="...")


async def main():
# Let's login first, it's not necessary but makes things a bit smoother.
await client.login()

# let's get a manga
manga = await client.get_manga("...")

# ... byt we realise it is incorrect or has the wrong data.
# we'll submit a report for correction:
report = hondana.ReportDetails(
category=hondana.ReportCategory.manga,
reason=hondana.MangaReportReason.information_to_correct,
details="The attributed author of this manga is not correct.",
target_id=manga.id,
)

# and we send it off:
await client.create_report(report)

await client.close()
async with hondana.Client(client_id="...", client_secret="...") as client:
# let's get a manga
manga = await client.get_manga("...")

# ... but we realise it is incorrect or has the wrong data.
# we'll submit a report for correction:
report = hondana.ReportDetails(
category=hondana.ReportCategory.manga,
reason=hondana.MangaReportReason.information_to_correct,
details="The attributed author of this manga is not correct.",
target_id=manga.id,
)

# and we send it off:
await client.create_report(report)


asyncio.run(main())
22 changes: 9 additions & 13 deletions examples/updating_local_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,18 @@
import hondana


# Auth is not required for this process, so just a Client will work.
client = hondana.Client()


async def main():
current_tags = hondana.MANGA_TAGS
print(current_tags)

# Use the client convenience method to update the local cache
# This will also update the local store of them, they will be available on next module reload.
new_tags = await client.update_tags()
# Auth is not required for this process, so just a Client will work.
async with hondana.Client() as client:
current_tags = hondana.MANGA_TAGS
print(current_tags)

# Show the new changes.
print(new_tags)
# Use the client convenience method to update the local cache
# This will also update the local store of them, they will be available on next module reload.
new_tags = await client.update_tags()

await client.close()
# Show the new changes.
print(new_tags)


asyncio.run(main())
Loading

0 comments on commit c604846

Please sign in to comment.