I am using a FastAPI endpoint to do some sort of long polling and also aiopika to wait messages that a client is publishing to rabbitmq connection/channel/exchange/queue.
My question: When I make a request to the endpoint it is blocked waiting for a message to arrive but as you can see in the below snipped if I put a print() instruction before it starts consuming it is not shown until a message arrives. Why this happens?
@router.post("/long_polling")
async def long_polling(request):
device_id = "1234"
print("THIS IS NOT PRINTED UNTIL A MESSAGE IS PUBLISHED!!!")
connection = await aio_pika.connect("amqp://user:pwd@rabbitmq:5672/")
async with connection:
channel = await connection.channel()
exchange = await channel.declare_exchange("exchange", aio_pika.ExchangeType.TOPIC)
queue = await channel.declare_queue("")
await queue.bind(exchange, routing_key="{}.outgoing".format(device_id))
print("NOT PRINTED UNTIL A MESSAGE ARRIVE ALTHOUGH BEFORE CONSUMING")
# START CONSUMING
async with queue.iterator() as queue_iter:
async for message in queue_iter:
async with message.process():
print(message.body)
return
When I published a message, the endpoint returns properly, so just to know why the previous instructions are not executed until a new message arrives.