1

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)
0

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

what will be returned by return validate_input(a) if a is < 10? Then validate_input(a) will not return anything and therefore the "outer" return will not end the function?
Obviously it needs to be handled, add another return Response (response = "a <10", status = 200), if that's how you want to handle it, I just reused your code, I don't know what you need to do specifically
1

As you are returning two things in the function. So you can just call function and return it which will return.

[...]
return validate_input(a)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.