Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

init_app doesn't seem to work with lifespans #77

Closed
ChrsPi opened this issue Nov 20, 2023 · 2 comments
Closed

init_app doesn't seem to work with lifespans #77

ChrsPi opened this issue Nov 20, 2023 · 2 comments

Comments

@ChrsPi
Copy link

ChrsPi commented Nov 20, 2023

Versions: fastapi: 0.103.2, fastapi-mqtt: 2.0.0

When I use a fastapi lifespan (e.g. in order to setup a db connection) the init_app method does not seem to work anymore. The client will not connect. I guess because the now deprecated startup and shutdown events won't get triggered when using lifespans.

Lifespan documentation: https://fastapi.tiangolo.com/advanced/events/

The init_app method for reference:

def init_app(self, app: FastAPI) -> None:  # pragma: no cover
    @app.on_event("startup")
    async def startup():
        await self.connection()

    @app.on_event("shutdown")
    async def shutdown():
        await self.client.disconnect()

Calling the connection() and disconnect() methods themselves from the lifespan then works again:

...
mqtt_config = MQTTConfig(host=settings.mqtt_host, port=settings.mqtt_port)
mqtt = FastMQTT(config=mqtt_config)

@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncGenerator[None, None]:
    """Run tasks before and after the server starts.

    Specifically, we initialize the database models before the server starts
    to ensure that the database has the correct schema.
    """
    try:
        init_models()
        await mqtt.connection()

    except ConnectionRefusedError as exc:
        raise ConnectionRefusedError("Failed to connect to the database") from exc
    yield
    await mqtt.client.disconnect()

Is it an error on my part with using the lifespan? Otherwise adding a hint for this to the official documentation will help others.

@azogue
Copy link
Collaborator

azogue commented Nov 23, 2023

When I use a fastapi lifespan (e.g. in order to setup a db connection) the init_app method does not seem to work anymore.

Is it an error on my part with using the lifespan?

Hi @ChrsPi, it's normal. When using a lifespan method to setup, yield, and shutdown the app, that init_app method is not called anymore, and the connection and disconnection has to be called the way you do in the snippet 👍

Take into account that disconnections and re-connections to the MQTT broker are also not managed by default, but you can define callbacks with @mqtt.on_connect() and @mqtt.on_disconnect() decorators to manage those events

Otherwise adding a hint for this to the official documentation will help others.

For sure! PRs to improve docs are always welcome 🙏

@ChrsPi
Copy link
Author

ChrsPi commented Nov 23, 2023

Thanks a lot for your response and explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants