Synchronous Usage with wattpad
¶
wattpad
is an asynchronous package. That means, you need to use the async
and await
keywords to use the package.
What is Async?¶
A simple analogy: You're a painter who has to deliver 30 painted pots by the end of the day. Each pot takes fifteen minutes to paint, and another 45 to dry. That's an hour in total.
The Synchronous Way¶
You paint one pot, wait for it to dry (staring doesn't make it go faster. Pots aren't microwaves.), and paint another. All in all, this takes you 30 hours, putting you past the deadline. (and in a state of sleep deprivation, that isn't new though.)
The Asynchronous Way¶
Being a hyper-efficient being, you leverage your common sense and realize that you can paint a different pot while the previous one dries. That means, it'll take you just 8 hours and 15 minutes. That's incredible.
Similarly, in asynchronous code, you have an event loop. This is the painter. Let's switch the task from painting pots to retrieving data from a database. You have 30 intensive requests to make.
Given that the database won't crash, your goal is to get the results as fast as possible.
Fire a request, while the database processes it, fire another, and keep doing other tasks until the database has a result for the first request. When the pot is painted, we want to package it and set it aside. Similarly, when a function is ready to continue, we return our attention to it.
import asyncio
async def get_database_results():
# something time taking
return results
async def one():
results = await get_database_results()
# processing
print(results)
async def two():
results = await get_database_results()
# processing
print(results)
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(one())
tg.create_task(two())
asyncio.run(main())
In the above code:
- We start
one
, while we await the results from the database, we starttwo
. - The
await
keyword tells the event loop to switch its attention to another task. When the function is ready to continue, it signals the same to the event loop, which shifts its attention when the other task enters anawait
.
async
is simple to use. You can get started by simply prefixing your function with an async
.
Using wattpad
in a synchronous environment¶
There are various situations where asynchronous structures aren't preferred. For such situations specifically:
import asyncio
from wattpad import User
u = User("WattpadBooks")
asyncio.run(u.fetch())
print(u.data.description)
This is completely synchronous.
Note: asyncio.run(func())
will not work in a Jupyter notebook. You can:
- Use
await func()
directly - Use
asyncio.get_event_loop().run_until_complete(func())
For more, see this.
TheOnlyWayUp © 2024