Skip to content

Access by Name#

Sometimes, you may need to use a different name for the argument (not the one under which it is stored in the context) or get access to specific parts of the object. To do this, simply specify the name of what you want to access, and the context will provide you with the object.

from faststream import Context, FastStream
from faststream.kafka import KafkaBroker, KafkaMessage

broker = KafkaBroker("localhost:9092")
app = FastStream(broker)


@broker.subscriber("test-topic")
async def handle(
    msg: KafkaMessage = Context("message"),
    correlation_id: str = Context("message.correlation_id"),
):
    assert msg.correlation_id == correlation_id
from faststream import Context, FastStream
from faststream.rabbit import RabbitBroker, RabbitMessage

broker = RabbitBroker("amqp://guest:guest@localhost:5672/")
app = FastStream(broker)


@broker.subscriber("test-queue")
async def handle(
    msg: RabbitMessage = Context("message"),
    correlation_id: str = Context("message.correlation_id"),
):
    assert msg.correlation_id == correlation_id

This way you can get access to context object by its name

    msg: KafkaMessage = Context("message"),
    msg: RabbitMessage = Context("message"),

This way you can get access to context object specific field

    correlation_id: str = Context("message.correlation_id"),
    correlation_id: str = Context("message.correlation_id"),

Last update: 2023-09-21