0

I need to make a post request that passes parameters to another function. The problem is that this function takes a long time to process and the request eventually results in timeout. I want to create an asynchronous call to initialize the function so that it continues to execute in the background even after the post request ends.

class Assincrono(Resource):
    ''' make a assyncronous post request '''

    async def post(self):
        async with aiohttp.ClientSession() as session:
            with session.post('localhost:5000/classificator/') as resp:
                return await resp.text()

class TrainResource(Resource):
    ''' route /classificator'''

    def post(self):
        content = request.json
        result = ServiceModel().decision(content)
        if result['status'] == 'error':
            return Response(json.dumps(result), status=400, mimetype='application/json')
        return Response(json.dumps(result), status=201, mimetype='application/json')


Error:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
    <title>TypeError: Object of type 'coroutine' is not JSON serializable // Werkzeug Debugger</title>

Nick K9
  • 3,885
  • 1
  • 29
  • 62

1 Answers1

1

The typical way asynchronous requests are handled in Flask is by using a message queue, like Redis (e.g. rq). You add tasks to the queue as needed, and have a worker process which pulls them off and processes them at leisure. Miguel Grinberg has an excellent post on his blog explaining how to achieve this, with lots of code examples.

Nick K9
  • 3,885
  • 1
  • 29
  • 62