Alejandro A
Alejandro A

Reputation: 1190

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.

Upvotes: 0

Views: 74

Answers (2)

joshua
joshua

Reputation: 335

In [5]: def test(): 
   ...:     return 1,2 if False else 3,4 

In [6]: test()                                                                  
Out[6]: (1, 3, 4)

In [7]: def test(): 
   ...:     return (1,2) if False else (3,4) 
In [8]: test()                                                                  
Out[8]: (3, 4)

so,change your code like this

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

Upvotes: 1

Alejandro A
Alejandro A

Reputation: 1190

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

Upvotes: 0

Related Questions