返回烧瓶端点 json/status 代码时出错

Error returning flask endpoint json/status code

如果请求成功,我有一个端点可以正常工作,否则会使代码崩溃(不是预期的行为)

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

当在数据库中找到 car_id --> 确定。

当未找到 car_id 时,res 为 None 并且预期 return 为 400,但 returns 为 500,并出现以下错误:

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

知道为什么吗?同样的结构json+状态码

好的,所以:

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

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

我预计 return 'True','A'.

正确的是

def hola():
    condition = True
    return ('True',"A") if condition else ('False','B')
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)

所以,像这样更改您的代码

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