0

I have a Flask controller action with the following input validation routine, is there a way to write it more succinctly?

if 'firstName' and \
    'lastName' and \
    'age' \
not in request.json:
    return flask.abort(400)

Perhaps something like this, although I'm not sure how to get the and operators to work:

mandatory_fields = ['firstName', 'lastName', 'age']
if mandatory_fields not in request.json:
        return flask.abort(400)

Is the second code snippet possible?

00101010
  • 11
  • 2

1 Answers1

1

You can use all() method like this:

fields = ["a", "b", "c"]
a_hash = {"a": 1, "b": 2, "c": 3, "d": 4}
if all(field in a_hash for field in fields):
    print("All good")
# prints "All good"

fields = ["a", "b", "c", "e"]
a_hash = {"a": 1, "b": 2, "c": 3, "d": 4}
if any(field not in a_hash for field in fields):
    print("All bad")
# prints "All bad"
mishik
  • 9,973
  • 9
  • 45
  • 67