简体   繁体   English

通过Flask返回空的JSON

[英]return empty JSON by Flask

I have a simple functions, which should returns JSON. 我有一个简单的函数,应该返回JSON。

@app.route('/storage/experiments', methods=['GET'])
def get_experiments():
    if not request.json:
        abort(400)
    experiments = db['experiments']
    cursor = experiments.find(request.get_json())
    print(dumps(cursor))
    resp = Response(response=dumps(cursor),
    status=200, \
    mimetype="application/json")
    return resp

print(dumps(cursor)) shows print(dumps(cursor))显示

[{"current": "11", "date": "12.12.2001", "_id": {"$oid": "551c7b642349c517f5fa5223"}, "name": "xaxa", "voltage": "34"}]

but returns empty brackets [] 但返回空括号[]

you can use the jsonify function from the flask module. 您可以使用flask模块的jsonify函数。

Edit Chrisitian is right I didn't notice that you were using a list. 克里斯蒂安( Edit Chrisitian)是对的,我没有注意到您正在使用列表。 Anyways here's a decorator that I wrote exactly to solve this problem: Json decorator . 无论如何,这是我为解决这个问题而写的一个装饰器: Json decorator Hope this helps. 希望这可以帮助。

I guess this is happneing because your database cursor (I don't know what database framework you use. sqlalchemy ?) points at the end of your dataset when you want to return it, because your print() -statement was already iterating over it. 我想这是因为happneing数据库光标(我不知道你用什么数据库框架。 sqlalchemy ?)在您的数据集的终点,当你想退货,因为你print()语句来已经在它遍历。 It should work with this code when you just comment out the print() statement, because I can't see any other error in this code: 当您只注释掉print()语句时,它应该与此代码一起工作,因为在此代码中我看不到任何其他错误:

@app.route('/storage/experiments', methods=['GET'])
def get_experiments():
    if not request.json:
        abort(400)
    experiments = db['experiments']
    cursor = experiments.find(request.get_json())
    #print(dumps(cursor))
    resp = Response(response=dumps(cursor),
    status=200, \
    mimetype="application/json")
    return resp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM