[Python] asyncio CancelledError when using aio_pika and httpx

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I am using aio_pika library to read messages from RabbitMQ queue. For every message that arrives I call process_message method which calls logIn method (which uses httpx library). This is the RabbitMQ code:

    async def callback(message: aio_pika.IncomingMessage):
    async with message.process():
    try:
    json_data = json.loads(message.body)
    await process_message(json_data)
    print("Received JSON:", json_data)

    except json.JSONDecodeError:
    print("Received invalid JSON")

    async def get_data():
    connection, channel, queue = await init_rabbitmq_connection()
    await queue.consume(callback)
    print("Waiting for JSON messages. To exit press CTRL+C")
    await asyncio.Future()

    async def main():
    await get_data()

    if __name__ == "__main__":
    asyncio.run(main())


    This is process_message code:

    async def process_message(json_data):
    try:
    async with httpx.AsyncClient(verify=False) as client:
    await logIn(client)
    except asyncio.CancelledError:
    print("Task was cancelled")


    This is logIn code:

    async def logIn(client):
    login_url="https://page_name/login"

    payload = {
    'IDToken1': 'user',
    'IDToken2': 'pass'
    }

    try:
    print("Sending request...")
    response = await client.post(login_url, data=payload)
    print("Request sent.")

    if response.status_code in (200, 302):
    try:
    print("Login successful!")
    json_data = response.json()
    if json_data.get("code") == "SUCCESS":
    print("Login successful!")
    else:
    print("Login failed:", json_data)
    except asyncio.CancelledError:
    print("Login request was cancelled")

    except httpx.RequestError as e:
    print(f"Request failed: {e}")


    I am getting the "Login request was cancelled" error and I don't see why. Log in works when I call it on its own, without using the queue, and reading from queue also works well. But with those two combined, I am getting CancelledError.

    Continue reading...

Compartilhe esta Página