github reflex-dev/reflex v0.5.2

latest releases: v0.6.8, v0.6.7, v0.6.6.post3...
7 months ago

New Features

Lifespan Tasks

A lifespan task is either a coroutine which runs while the backend server is running and is cancelled when the server stops, or it can be an asynccontextmanager in which case it will run at server startup until yield is called, then it will resume as the server is shutting down. In either case, the task is started and stopped during hot reload.

Any keyword arguments passed to app.register_lifespan_task will be passed to the coroutine/contextmanager. If the coroutine takes a parameter called app, this will be an instance of the underlying FastAPI object.

Sample Code
import asyncio
from contextlib import asynccontextmanager


def fake_answer_to_everything_ml_model(x: float):
    return x * 42


ml_models = {}


@asynccontextmanager
async def setup_model(app: FastAPI):
    # Load the ML model
    ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
    yield
    # Clean up the ML models and release the resources
    ml_models.clear()


async def long_running_task(foo, bar):
    print(f"Starting {foo} {bar} task")
    some_api = SomeApi(foo)
    try:
        while True:
            updates = some_api.poll_for_updates()
            other_api.push_changes(updates, bar)
            await asyncio.sleep(5)  # add some polling delay to avoid running too often
    except asyncio.CancelledError:
        some_api.close()  # clean up the API if needed
        print("Task was stopped")


app = rx.App()
app.register_lifespan_task(setup_model)
app.register_lifespan_task(long_running_task, foo=42, bar=os.environ["BAR_PARAM"])

Improvements

Bug Fixes

Readme Updates

Other Changes

New Contributors

Full Changelog: https://github.com/reflex-dev/reflex/compare/v0.5.1..v0.5.2

Don't miss a new reflex release

NewReleases is sending notifications on new releases.