You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
The text was updated successfully, but these errors were encountered:
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 🙏
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:
Calling the connection() and disconnect() methods themselves from the lifespan then works again:
Is it an error on my part with using the lifespan? Otherwise adding a hint for this to the official documentation will help others.
The text was updated successfully, but these errors were encountered: