question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] How to get async functionality to work?

See original GitHub issue

First check

  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.

Description

How can I properly utilize the asynchronous within a route? The following code takes 4 seconds to complete a call to /async route, while I expect it to only take 2 seconds.

import time
from fastapi import FastAPI

app = FastAPI()

async def get_a():
    time.sleep(2)
    return 'a'

async def get_b():
    time.sleep(2)
    return 'b'

@app.get("/async")
async def asynchronous():
    a = await get_a()
    b = await get_b()
    return {
        'a': a,
        'b': b,
    }

Additional context

Environment is running off docker container tiangolo/uvicorn-gunicorn-fastapi:python3.7 App was was started with uvicorn app.app:app --reload --host 0.0.0.0

Add any other context or screenshots about the feature request here.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
jscottcronincommented, Feb 7, 2020

@euri10 - asyncio.sleep did work.

Instead of writing a dummy function like

async def get_b():
    asyncio.sleep(2)
    return 'b'

How would I write a function that makes requests like the following. Note: this request takes 2x as long as I expect, where each request takes about the same amount of time. I have tried with both requests and httpx libraries.

async def get_taxonomy():
    return httpx.post(TAXONOMY_ENDPOINT, json=TAXONOMY_PAYLOAD).json()

async def get_attributes():
    return httpx.post(ATTRIBUTE_ENDPOINT, json=ATTRIBUTE_PAYLOAD).json()

@app.get("/async")
async def asynchronous():
    return {
        'taxonomy': await get_taxonomy(),
        'attributes': await get_attributes(),
    }
2reactions
reynoldsdjcommented, Feb 12, 2020

This is a “how to use asyncio in Python” and is unrelated to FastAPI.

The await keyword blocks the execution of the remaining code in the function, so each await causes the code in that function to execute synchronously (await causes the event loop to execute the next event scheduled on the event loop).

You will want to use asyncio.create_task() or asyncio.gather() to schedule and execute coroutines on the event loop. This will allow both httpx methods to make their requests and wait for their responses in an asynchronous manner.

Note: If you are used to Javascript async/await or promises, the Python asyncio machinery does not function in quite the same manner.

Read more comments on GitHub >

github_iconTop Results From Across the Web

async function - JavaScript - MDN Web Docs - Mozilla
The resolved value of the promise is treated as the return value of the await expression. Use of async and await enables the...
Read more >
Async Await JavaScript Tutorial – How to Wait for a Function to ...
Firstly, setTimeout is delegated to the browser, which does the work and puts the resulting function in the macrotask queue. · Secondly fetch...
Read more >
How to call an async function? - javascript - Stack Overflow
We can use the await keyword inside this function now. The await keyword makes it possible to 'wait' for a promise to be...
Read more >
Tips For Using Async/Await in JavaScript - YouTube
Async / Await is a much cleaner syntax for working with promises than ... Let's take a look at how to convert an...
Read more >
Async IO in Python: A Complete Walkthrough
Using await and/or return creates a coroutine function. To call a coroutine function, you must await it to get its results. It is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found