И, честно говоря, оба примера практически ничего не объясняют и слишком сложны.< /p>
Допустим, я хочу печатать Hello каждые 30 секунд. Моя функция будет:
Код: Выделить всё
import asyncio
async def hello(interval: int) -> None:
while True:
try:
print('HELLO')
# let's suppose that our print may raise error for some reason
except Exception as e:
print('BOOM Error!', e)
# don't understand way we have to ignore CancelledError?
except asyncio.exceptions.CancelledError:
pass
finally:
await asyncio.sleep(interval)
Я пытался понять пример, но слишком много вещей для меня непонятно. Смотрим первый пример
Код: Выделить всё
# do we really need this AppKey? In other examples usual string identifier is used
valkey_listener = web.AppKey("valkey_listener", asyncio.Task[None])
...
async def listen_to_valkey(app: web.Application) -> None:
...
# Looks like that is endless loop? Same as `while True` in my example
async with r.pubsub() as sub:
await sub.subscribe(channel)
...
async def background_tasks(app: web.Application) -> AsyncIterator[None]:
# okay, that is a only line I can understand
app[valkey_listener] = asyncio.create_task(listen_to_valkey(app))
# why here is yield? Is it separating something?
yield
print("cleanup background tasks...")
# Already canceling? Why? Do we already started the task?
app[valkey_listener].cancel()
# as I asked in my example, what is a purpose to ignore canceling?
with suppress(asyncio.CancelledError):
# Okay, looks like we finally start endless task here?
await app[valkey_listener]
def init() -> web.Application:
app = web.Application()
...
# okay, here is we are adding background task to context it is clear
# https://docs.aiohttp.org/en/stable/web_advanced.html#cleanup-context
app.cleanup_ctx.append(background_tasks)
...
Подробнее здесь: https://stackoverflow.com/questions/790 ... in-aiohttp