Issue
I'm trying to handle parameters in the routing path in Flask:
@app.route('/example/<id>', methods=['GET'])
def tasks(id):
if id == 1:
obj = FirstTask()
elif id == 2:
obj = SecondTask()
elif id == 3:
obj = ThirdTask()
result = obj.start()
return make_response(jsonify({ 'data': { result } }), 200)
After run, I get following error:
"local variable 'obj' referenced before assignment"
I've never programmed in Python and I don't know how to solve this.
Solution
You have two bugs, working in concert:
- You're comparing apples to oranges, that is strings to integers.
- You don't handle invalid
id
s.
The solution for the first is to add a converter to the route (int:
), the solution for the second is to add an else
:
from flask import abort
@app.route('/example/<int:id>', methods=['GET'])
def tasks(id):
if id == 1:
obj = FirstTask()
elif id == 2:
obj = SecondTask()
elif id == 3:
obj = ThirdTask()
else:
abort(404)
result = obj.start()
return make_response(jsonify({ 'data': { result } }), 200)
Answered By - Jasmijn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.