【问题标题】:How to send the cursor from a mongo db find query as a result in flask如何在烧瓶中从 mongodb 查找查询发送光标
【发布时间】:2021-08-17 02:15:20
【问题描述】:

我希望能够查询我的 mongo 数据库并获取我的 stocksCollection 集合中所有条目的结果。我正在使用allStocks = list(stocksCollection.find({})),它为我提供了该集合中所有条目的列表。但是,当我尝试将此作为对 get 请求的响应返回时,我收到错误:

TypeError: The view function did not return a valid response. 
The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.

这是我用来得到这个的简单代码:

@app.route("/stocks", methods=['GET'])
def getAllStocks():
    return list(stocksCollection.find({}))

我也试过:return stocksCollection.find({})(错误,因为它是一种类型:游标)和

allStocks = list(stocksCollection.find({}))
return {'data': allStocks}

但这只是给了我错误TypeError: Object of type ObjectId is not JSON serializable。关于我可以将此光标更改为何种格式的任何想法,以便我能够将其返回到我的 api 调用(这不会直接提供给网页,只是被前端调用以进行一些计算)

【问题讨论】:

    标签: python json mongodb flask cursor


    【解决方案1】:

    创建 JSONEncoder 类以使 ObjectId JSON 可序列化

    import json
    from bson import ObjectId
    
    class JSONEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, ObjectId):
                return str(o)
            return json.JSONEncoder.default(self, o)
    

    然后使用如下 JSONEncoder 类(在 json.dumps 中)并使 _id 值 JSON 可序列化并将数据附加到新列表中返回。

    @app.route("/stocks", methods=['GET'])
    def getAllStocks():
        output = []
        all_data = stocksCollection.find({})
        for data in all_data:
            data['_id'] = json.dumps(data['_id'], cls=JSONEncoder)
            output.appned(data)
        return {"data": output}
    

    我想这会解决你的问题。

    【讨论】:

    • 不,那么烧瓶只会给我这个错误:TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.
    • 您不能将列表作为 api 响应返回。 getAllStocks() 已更新。现在这将起作用。
    • 不,然后我得到错误:unhashable type: 'dict'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多