Search code examples
pythonflaskwerkzeug

Error returning flask endpoint json/status code


I have an endpoint that works fine if the request is scucessfull and crashes the code otherwise (not expected behavior)

class CarbyID(Resource):
    def get(self, car_id):
        json_return = {'car_id': car_id}
        try:
            res = db_query.read(car_id) #gets the data from the databse
            json_return['data'] = res
            return json_return, 200 if res else json_return, 400
        except:
            return json_return,505

When the car_id is found in the database --> OK.

When the car_id is not found, res is None and expected to return a 400, but returns a 500 with the following error:

  File "\Lib\site-packages\werkzeug\datastructures.py", line 1091, in extend
    for key, value in iterable:
ValueError: too many values to unpack (expected 2)

Any idea why? It's the same structure json+status code.


Solution

  • Ok, so:

    def hola():
        condition = True
        return 'True',"A" if condition else 'False','B'
    

    Returns 'True','A','B'.

    I expected to return 'True','A'.

    Correct would be

    def hola():
        condition = True
        return ('True',"A") if condition else ('False','B')