mode-streaming
Mode-streaming is a Python library built on top of AsyncIO, designed to simplify asynchronous service-based programming. It allows users to define, start, stop, restart, and supervise services, forming a graph of dependencies. This project is a community-maintained fork of the original 'Mode' project, with a focus on continuous releases, code quality, and support for modern Python versions. The current version is 0.4.1.
Warnings
- breaking Version 0.3.6 was yanked due to missing functionality, and 0.4.0 was released to mitigate 'backward-breaking incompatibilities'. Users upgrading from versions prior to 0.4.0 should carefully review the changelog for potential breaking changes.
- gotcha When integrating `mode-streaming` with blocking frameworks like Django or Flask, it's crucial to apply monkey-patching libraries like `gevent` or `eventlet` at the very top of your application's entry point. Failing to do so before other imports can lead to unexpected behavior or deadlocks.
- gotcha In versions prior to 0.4.1, the `Service` class could attempt to get an event loop during its initialization phase, potentially leading to issues if no event loop was yet set. This was addressed in version 0.4.1.
Install
-
pip install -U mode-streaming
Imports
- Service
from mode import Service
- Worker
from mode import Worker
Quickstart
import asyncio
from mode import Service, Worker
class MyService(Service):
async def on_start(self) -> None:
print("MyService started!")
self.add_background_task(self.my_periodic_task)
@Service.timer(1.0)
async def my_periodic_task(self) -> None:
print("Periodic task running...")
async def on_stop(self) -> None:
print("MyService stopped.")
async def main():
service = MyService()
worker = Worker(service, loglevel="info")
# In a real application, you'd execute from command line
# For quickstart, manually manage lifecycle (or use execute_from_commandline)
try:
await worker.start()
await asyncio.sleep(3)
finally:
await worker.stop()
if __name__ == '__main__':
asyncio.run(main())