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.
asyncandawaitkeywords when not needed. Try to reduce them and it will work properly. \$\endgroup\$