10

Usage of async/await was presented in Flask 2.0. (https://flask.palletsprojects.com/en/2.0.x/async-await/)

I am using Flask-RestX so is it possible to use async/await in RestX requests handlers?

Something like:

@api.route('/try-async')
class MyResource(Resource):
    @api.expect(some_schema)
    async def get(self):
        result = await async_function()
        return result

is not working and when I try to reach this endpoint I'm getting error:

TypeError: Object of type coroutine is not JSON serializable

Is there any info on that?

Package versions:

flask==2.0.1
flask-restx==0.4.0

and I've also installed flask[async] as documentation suggests.

1 Answers1

2

I've gotten around this by using an internal redirect

@api.route('/try-async')
class MyResource(Resource):
    @api.expect(some_schema)
    def get(self):
        return redirect(url_for('.hidden_async'), code=307)

@api.route('/hidden-async', methods=['GET'])
async def hidden_async():
    result = await async_function()
    return result

Redirecting with code=307 will ensure any method and body are unchanged after the redirect (Link). So passing data to the async function is possible as well.

@api.route('/try-async')
class MyResource(Resource):
    @api.expect(some_schema)
    def post(self):
        return redirect(url_for('.hidden_async'), code=307)

@api.route('/hidden-async', methods=['POST'])
async def hidden_async():
    data = request.get_json()
    tasks = [async_function(d) for d in data]
    result = await asyncio.gather(tasks)
    return result