How to publish from a fastapi process? #2968
|
Hi all! I can't figure out how to publish from a fastapi process. We run a fastapi app with Example of faststream with two types of task (scheduled and simple async task) (ran with from faststream import FastStream
from faststream.redis import RedisBroker
from taskiq_faststream import BrokerWrapper
from taskiq_faststream import StreamScheduler
from taskiq.schedule_sources import LabelScheduleSource
broker = RedisBroker("redis://localhost:6379")
app = FastStream(broker)
@broker.subscriber("send-confirm-email")
async def send_confirm_email(email: str) -> None:
# sending confirmation email...
@broker.subscriber("in-channel")
async def handle_msg(user: str, user_id: int) -> str:
return f"User: {user_id} - {user} registered"
taskiq_broker = BrokerWrapper(broker)
taskiq_broker.task(
message={"user": "John", "user_id": 1},
channel="in-channel",
schedule=[{
"cron": "* * * * *",
}],
)
scheduler = StreamScheduler(
broker=taskiq_broker,
sources=[LabelScheduleSource(taskiq_broker)],
)Example of fastapi app (ran with from fastapi import FastAPI
app = FastAPI()
@app.get('/register')
async def register(data):
# doing something
await broker.publish(data.email, channel="send-confirm-email") # does not work, gives an error Exception <class 'faststream.exceptions.IncorrectState'>: Connection is not available yet. Please, connect the broker first
How to do it right? |
Replies: 1 comment
|
You don't need taskiq for this. The broker works on its own, so open it in the FastAPI lifespan and publish straight from the endpoint: from contextlib import asynccontextmanager
from fastapi import FastAPI
from faststream.redis import RedisBroker
broker = RedisBroker("redis://localhost:6379")
@asynccontextmanager
async def lifespan(app: FastAPI):
async with broker:
yield
app = FastAPI(lifespan=lifespan)
@app.get("/register")
async def register():
await broker.publish("john@example.com", channel="send-confirm-email")
return {"ok": True}
Keep the broker at module level like above. Create it inside Nothing changes on the FastStream side, Skip |
You don't need taskiq for this. The broker works on its own, so open it in the FastAPI lifespan and publish straight from the endpoint:
async with brokeronly connects and disconnects. There's nobroker.start()here on purpose. That's the call that launches subs…