pythonflaskflask-restx

Python/Flask: Return Message and Status Code to calling function?


I have a Flask App (build on top of the Flask Restx Resource class) and I've created a couple of try/except statements to validate the input of my app.

To make the code of the app more readable, I'd like to encapsulate these checks in a seperate function. But this introduces the challenge of returning the error message and Status Code correctly so that it can be handled by the API.

Is there a way to make the function return via the calling function or so?

# minimal example
from flask import Flask
from flask_restx import Api, Resource

app = Flask(__name__)
api = Api(app)

def validate_input(a):
    try:
        assert a < 10
    except:
        return "a >= 10", 500

@api.route("/<a>")
class BatchScorer(Resource):
    def get(self, a):

        # validate_input(a):

        # instead of?

        try:
            assert a < 10
        except:
            return "a >= 10", 500


if __name__ == "__main__":
    app.run(debug=True)

Solution

  • Add a return value to the checking function, and simply return the value returned by that function

    from flask import Flask, Response
    from flask_restx import Api, Resource
    
    app = Flask(__name__)
    api = Api(app)
    
    def validate_input(a):        
        if (a < 10):
            return Response(response="a < 10", status=200)
        else:
            return Response(response="a >= 10", status=500)
    
    @api.route("/<a>")
    class BatchScorer(Resource):
        def get(self, a):
            return validate_input(a)
    
    
    if __name__ == "__main__":
        app.run(debug=True)