【问题标题】:Return Pymongo result in Python Bottle在 Python Bottle 中返回 Pymongo 结果
【发布时间】:2014-08-02 16:01:18
【问题描述】:

我尝试实现一种“某种”个人 API 供我自己使用。我使用 Pymongo 在 Python Bottle 工作。这是我的代码:

@bottle.get('/getscore')
def getscore():
    mode = bottle.request.query.get("mode")

    results = scoredb.find({"mode":mode}).sort("score",-1).limit(5)

    return results (try also return str(results))

当我获取像www.mywebsite.com/getscore?mode=Mymodetest 这样的 url 时,我想返回此模式的前 5 个结果,得分最高。 (分数是一个数字字段)。

如果我使用return results 运行代码,我就有Unsupported response type: <type 'dict'> 。我在 SO 中发现了一个类似的问题,答案是使用 return str(results),但是有了这个,我有一个空页面。

【问题讨论】:

  • 尝试将results dict 转换为json。使用import json,然后使用return json.dumps(results)
  • @arun 我得到TypeError: &lt;pymongo.cursor.Cursor object at 0x109bda150&gt; is not JSON serializable

标签: python mongodb pymongo


【解决方案1】:

我没有使用json 库,而是尝试了这个,它可以工作。

from bson.json_util import dumps

dumps(results)

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 2019-09-18
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    相关资源
    最近更新 更多