Asyncio Event Driven State Machine
Build an event-driven state machine with asyncio for protocol parsing and workflow orchestration.
Code
import asyncio
from enum import Enum, auto
class State(Enum):
IDLE = auto()
PROCESSING = auto()
DONE = auto()
class StateMachine:
def __init__(self):
self.state = State.IDLE
self.queue = asyncio.Queue()
async def run(self):
while self.state != State.DONE:
event = await self.queue.get()
await self.handle(event)
async def handle(self, event):
if self.state == State.IDLE and event == 'start':
self.state = State.PROCESSING
elif self.state == State.PROCESSING and event == 'finish':
self.state = State.DONEReport a problem with this exampleOpens a pre-filled issue on GitHub.