0

I'm trying to make a POST request to a localhost address I've set inside the same python file but I am getting the error ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

Here's my code:

@app.route('/callback_work/', methods=['POST'])
async def callback_work():
    content_type = request.headers.get('content-type')
    if (content_type == 'application/json'):
        request_json = await request.get_json()
        print(request_json)
        return 'Callback done'
    else:
        return 'Content-Type not supported!'

async def capture_callback(request_json):
    requests.post('http://localhost:5000/callback_work/',
                  json=request_json, timeout=2, headers={"Content-Type": "application/json"})

I am already providing the request_json through another function and I know it's valid and it exists. Also, I've been sending POST requests through Postman all of this time and everything was working fine. The timeout argument is there as a precaution since I was executing the script without it and it never stopped waiting for the POST request to be executed.

Do you thing there's a problem that both the function that handles the post request and the function that makes the post request, are in the same file?

Zoi
  • 7
  • 3
  • iirc requests is not async compatible, so whats happening is that you make a post requst, which blocks, so your callback doesnt get called. edit: yeah [requests is not async compatible](https://stackoverflow.com/q/9110593/7540911) – Nullman May 03 '22 at 12:39
  • @Nullman so, how do you think I should approach this? Should I delete the `aync` off the capture_callback function? Maybe it's a stupid question, I'm not that good with python, still learning – Zoi May 03 '22 at 13:25
  • you have several options: you can use multiple scripts/multiprocessing (not multithreading), or something like the `aiohttp` library which does have async requests – Nullman May 03 '22 at 13:27
  • 1
    @Nullman I did it using the aiohttp library and it worked like a charm, if you were to write it as an answer I could accept it! Thanks! – Zoi May 03 '22 at 13:42

1 Answers1

0

the requests module is not async-able, even in an async funciton it will block. what happaned in your case is that your post request blocks and so your callback is unable to respond. you have two general options:

  • use an async compatible library like aiohttp
  • use multiple processes either by running multiple scripts or by multiprocessing
Nullman
  • 4,179
  • 2
  • 14
  • 30