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

Update FastAPI doc to use dependency injection #321

Merged
merged 1 commit into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

- Bump paho-mqtt to 2.1 (@empicano in #305)
- Migrate to paho-mqtt callback v2 (@empicano in #313)
- Update FastAPI example in the documentation (@odie5533 in #321)

### Fixed

Expand Down
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):
async 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
Loading