1
\$\begingroup\$

I am new to asynchronous programming in python. Below are two scripts(which perform the same operation) one in Fastapi + aiohttp while other is basic Flask + requests library:

## Flask

def fetch1(url):
    x = requests.get(url)                 # First hit to the url 
    data = x.json()                       # Grab response
    return fetch2(data['uuid'])           # Pass uuid to the second function for post request

def fetch2(id):
    url2 = "http://httpbin.org/post"
    params = {'id': id}
    x = requests.post(url2, json=params)
    return x.json() 

@app.route('/')
def main():
    url = 'http://httpbin.org/uuid'
    data = fetch1(url)    
    return {"message":"done"}

and the fastapi couterpart:

async def fetch1(session, url):
    async with session.get(url) as resp:                
        data = await resp.json()                       
        return await fetch2(session, data['uuid'])     

async def fetch2(session, id):
    url2 = "http://httpbin.org/post"
    params = {'id': id}
    async with session.post(url2, json=params) as resp:
        return await resp.json()


@app.get("/")
async def main():
    url = 'http://httpbin.org/uuid'
    async with aiohttp.ClientSession() as session:
        data = await fetch1(session, url)
        return {"message":"done"}

As a sample benchmark testing (Using Apache Bench), I had fired 500 requests at 100 concurrency, while Flask took 7 seconds(approx) to complete the operation fastapi takes 4.5 to do the same(which is not that great).Is my async code blocking in nature or Am I missing something.Any help will be appreciated.

\$\endgroup\$
2
  • \$\begingroup\$ There are too many async and await keywords when not needed. Try to reduce them and it will work properly. \$\endgroup\$ Commented Mar 8, 2021 at 6:20
  • \$\begingroup\$ @Vishnudev ,what changes would you suggest in the above code? \$\endgroup\$ Commented Mar 10, 2021 at 5:48

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.