Skip to content

Commit

Permalink
Update FastAPI doc to use dependency injection
Browse files Browse the repository at this point in the history
* Update the doc example for integration with FastAPI to use
  FastAPI's dependency injection for the MQTT client
  • Loading branch information
odie5533 committed Jul 17, 2024
1 parent d3e058d commit b0ca433
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions docs/alongside-fastapi-and-co.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ With [FastAPI](https://github.com/tiangolo/fastapi) (`0.93+`) and [Starlette](ht

```python
import asyncio
from typing import Annotated
import aiomqtt
import contextlib
import fastapi
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI


async def listen(client):
Expand All @@ -19,8 +20,12 @@ async def listen(client):
client = None


@contextlib.asynccontextmanager
async def lifespan(app):
def get_mqtt():
yield client


@asynccontextmanager
async def lifespan(app: FastAPI):
global client
async with aiomqtt.Client("test.mosquitto.org") as c:
# Make client globally available
Expand All @@ -39,11 +44,11 @@ async def lifespan(app):
pass


app = fastapi.FastAPI(lifespan=lifespan)
app = FastAPI(lifespan=lifespan)


@app.get("/")
async def publish():
async def publish(client: Annotated[aiomqtt.Client, Depends(get_mqtt)]):
await client.publish("humidity/outside", 0.38)
```

Expand Down

0 comments on commit b0ca433

Please sign in to comment.