python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.14k stars 333 forks source link

How do I use async/await with flask-restx? #600

Open airedwin opened 4 months ago

airedwin commented 4 months ago

Ask a question I have a simple route like

@ns_async.route('/async')
class AsyncResource(Resource):
    async def post(self,):

        await somefunction()

        return jsonify({
            'status': 'success'
        }), 200

when this route is called, i get an error saying that AsyncResource.post wasn't awaited "RuntimeWarning: coroutine 'AsyncResource.post' was never awaited"

Additional context the same function works when using normal flask[async]

@flask_app.route('/async', method=["POST"])
async def asyncfunc():

    await somefunction()

    return jsonify({
        'status': 'success'
    }), 200
alpha8133 commented 4 months ago

The error you're encountering, "RuntimeWarning: coroutine 'AsyncResource.post' was never awaited," occurs because the async function somefunction() is not being awaited within the post method of the AsyncResource class. To address this issue, you should await the somefunction() call within the post method. Here's the modified code: @ns_async.route('/async') class AsyncResource(Resource): async def post(self,):

Await the somefunction() call

    await somefunction()

    return jsonify({
        'status': 'success'
    }), 200

By incorporating the await keyword before somefunction(), you ensure that the asynchronous operation is properly awaited, resolving the runtime warning and allowing the code to function as expected.

airedwin commented 4 months ago

The error you're encountering, "RuntimeWarning: coroutine 'AsyncResource.post' was never awaited," occurs because the async function somefunction() is not being awaited within the post method of the AsyncResource class. To address this issue, you should await the somefunction() call within the post method. Here's the modified code: @ns_async.route('/async') class AsyncResource(Resource): async def post(self,): # Await the somefunction() call await somefunction()

    return jsonify({
        'status': 'success'
    }), 200

By incorporating the await keyword before somefunction(), you ensure that the asynchronous operation is properly awaited, resolving the runtime warning and allowing the code to function as expected.

thanks for the response, but I did await, is it not showing in my example?

the error that i am getting makes me think that whatever flask-restx is handling the call to AsyncResource.post() isn't using await

airedwin commented 4 months ago

this person at stackoverflow https://stackoverflow.com/questions/68115481/is-it-possible-to-use-flask-restx-wih-flasks-2-0-async-await also asked the same question with no realistic answer

engFelipeMonteiro commented 1 month ago

related to issue #366