Error [ERROR] Exception occurred while handling on async code

Next code works fine if I use time.sleep(0.1) instead of await asyncio.sleep(0.1)

On await asyncio.sleep(0.1) I am getting error:

 [ERROR] Exception occurred while handling uri: 'http://127.0.0.1:8000/api/new-answer'

My Code:

@app.route("/api/new-answer", methods=["POST"])
async def new_answer(request):

    r=requests.post(url, json=json_obj, headers={"Accept":"application/json", "Authorization": "bearer " + my_token}) # формат ответа: {'id': 53, 'status': 'new'}
    answer = r.json()

    if r.status_code == 200:
        while(True):
            await asyncio.sleep(0.1)
            # time.sleep(0.1)
            url = "https://site.com/v2/complex/status?id=" + str(latest_status_id)
            r=requests.get(url, headers={"Accept":"application/json", "Authorization": "bearer " + my_token})
            data = r.json()
            if data['status'] == 'completed':
                pass # some logic here

P.S. the answer from server may take up to 2 minutes.

You should be using https://github.com/encode/httpx instead of requests because it has an async mode that won’t block Sanic from serving other requests at the same time. Additionally, you may need to increase your app.config.RESPONSE_TIMEOUT which is by default only 60 seconds. I think your code fails because it takes longer than that timeout, but without any await inside your loop the timeout-enforcing code of Sanic never gets to run.

Thanks! I migrate code to httpx, but continue to get this error.
Only RESPONSE_TIMEOUT helped. Is it normal?

Yes, it seems as expected. Using httpx won’t avoid the handler timing out if it actually takes more tha 60 seconds to run. But using long blocking calls within Sanic will cause a lot of weird issues, including that the timeouts are not properly enforced. So, if you are using await with httpx and have set the timeout to match your processing time, you have fixed it correctly.

@bubnenkoff, Do you need to wait for the response before you serve back a response on your endpoint?

Another alternative that would alleviate is pushing the task off to “the background.” I say it like that because it could mean a lot of things depending upon your needs and threshhold for complexity in this circumstance.