Thursday, 12 September 2013

Returning a response in Flask

Returning a response in Flask

I have a code like this
def find_user(user_id):
if not users.lookup(user_id):
return jsonify(success=False, reason="not found")
else:
return users.lookup(user_id)
@app.route(...)
def view1(...):
user = find_user(...)
if user:
do_something
return jsonify(success=True, ....)
The point is I have a helper function and if condition is met I want to
return the response right away. In this case if user is not found, I want
to return a request stating the request failed and give a reason.
The problem is because the function can also return some other values (say
a user object) .
Ideally this is the longer code
def view(...)
user = users.lookup(user_id)
if not user:
return jsonify(success=False....)
# if user is true, do something else
The whole point of the helper function find_user is to extract out common
code and then reuse in a few other similar apis.
Is there a way to return the response directly? It seems like this is a
deadend... unless I change how the code is written (how values are
returned...)

No comments:

Post a Comment