Python Async Extension
A Python async extension is a modular component that leverages Python's asyncio framework. If you wish to integrate existing Python code utilizing asyncio into a Nyra extension, the Python async extension offers the most straightforward and efficient solution.
Example: The Default Python Async Extension
Here’s how a Python async extension is structured:
import asyncio
from nyra import AsyncExtension, AsyncNyraEnv
class DefaultAsyncExtension(AsyncExtension):
async def on_configure(self, nyra_env: AsyncNyraEnv) -> None:
# Mock async operation, e.g. network, file I/O.
await asyncio.sleep(0.5)
async def on_init(self, nyra_env: AsyncNyraEnv) -> None:
# Mock async operation, e.g. network, file I/O.
await asyncio.sleep(0.5)
async def on_start(self, nyra_env: AsyncNyraEnv) -> None:
# Mock async operation, e.g. network, file I/O.
await asyncio.sleep(0.5)
async def on_deinit(self, nyra_env: AsyncNyraEnv) -> None:
# Mock async operation, e.g. network, file I/O.
await asyncio.sleep(0.5)
async def on_cmd(self, nyra_env: AsyncNyraEnv, cmd: Cmd) -> None:
cmd_json = cmd.to_json()
nyra_env.log_debug(f"DefaultAsyncExtension on_cmd: {cmd_json}")
# Mock async operation, e.g. network, file I/O.
await asyncio.sleep(0.5)
# Send a new command to other extensions and wait for the result. The
# result will be returned to the original sender.
new_cmd = Cmd.create("hello")
cmd_result = await nyra_env.send_cmd(new_cmd)
nyra_env.return_result(cmd_result, cmd)Each method simulates a delay using await asyncio.sleep().
FAQ
Aysnc loop for event handling
Create a queue: use
asyncio.Queue.Create an async task for event handling.
import asyncio
from nyra import AsyncExtension, AsyncNyraEnv
class DefaultAsyncExtension(AsyncExtension):
queue = asyncio.Queue()
loop:asyncio.AbstractEventLoop = None
async def on_start(self, nyra_env: AsyncNyraEnv) -> None:
self.loop = asyncio.get_event_loop()
self.loop.create_task(self._consume())
async def on_stop(self, nyra_env: AsyncNyraEnv) -> None:
self.queue.put(None)
async def _consume(self) -> None:
while True
try:
value = await self.queue.get()
if value is None:
self.ten_env.log_info("async loop exit")
break
# Code for processing values retrieved from the queue.
except Exception as e:
self.ten_env.log_error(f"Failed to handle {e}")Conclusion
Nyra's Python async extension offers a robust mechanism for handling long-running tasks asynchronously. By integrating Python's asyncio framework, the extension ensures that operations like network requests and file handling are executed efficiently without blocking other processes. This makes Nyra an ideal choice for building scalable, modular applications with advanced asynchronous capabilities.
Last updated