【问题标题】:Python/Bottle/MongoDB: Unsupported response type: <type 'dict'>Python/Bottle/MongoDB:不支持的响应类型:<type 'dict'>
【发布时间】:2012-03-10 15:17:36
【问题描述】:
@route('/locations', method='GET')
def get_location():
    entity = db['locations'].find({'coordinate2d': {'$near': [37.871593, -122.272747]}}).limit(3)
    if not entity:
        abort(404, 'No nearby locations')
    return entity

上面部分代码的响应是:

Error 500: Internal Server Error

Sorry, the requested URL 'http://localhost:8080/locations' caused an error:

Unsupported response type: <type 'dict'>

我如何从 mongo 中获取该信息作为 Bottle 可以返回为 JSON 的类型?

【问题讨论】:

  • 您是否尝试过分解问题,即用简单的字典文字替换 db.find 调用?如果它以这种方式工作,那么问题一定是与 Mongo 相关的。是不是,和瓶子有关。
  • @Helgi 我有,Bottle 当然可以使用常规字典文字。但它无法处理 MongoDB ObjectId。

标签: python pymongo bottle


【解决方案1】:

我在尝试返回 python 列表时收到此错误。我以为它会翻译成 JSON,但事实并非如此。它到达了bottle.py中处理可迭代对象的行,并在列表中找到了第一个dict并抛出了上面的错误。

为了解决这个问题,我只是将我的列表嵌入到一个字典中。

return {'response': []}

【讨论】:

【解决方案2】:

完整的解决方案是将db光标转换为列表,手动设置响应类型+自定义编码返回值

@route('/locations/:lat/:lng', method='GET')
def get_location(lat,lng):
    response.content_type = 'application/json'
    objdb = db.locations.find({'coordinate2d': {'$near': [lat,lng]}}, {'coordinate2d':bool(1)}).skip(0).limit(3)
    entries = [entry for entry in objdb]
    return MongoEncoder().encode(entries)

在我的例子中,产生这个:

[
    {
        "_id": "4f4201bb7e720d1dca000005",
        "coordinate2d": [
            33.02032100000006,
            -117.19483074631853
        ]
    },
    {
        "_id": "4f4201587e720d1dca000002",
        "coordinate2d": [
            33.158092999999994,
            -117.350594
        ]
    },
    {
        "_id": "4f42018b7e720d1dca000003",
        "coordinate2d": [
            33.195870000000006,
            -117.379483
        ]
    }
]

【讨论】:

  • 这很有帮助。我遇到了类似的问题,但是因为我不知道 MongoEncoder 来自哪里而遇到了问题。 只需返回条目就可以了。
【解决方案3】:

根据瓶子http://bottlepy.org/docs/dev/ 上的文档提及,您必须从@route 装饰器返回字符串。您必须返回带有数据或字符串的模板。

如果要生成 json,则必须更改 Content-Type

字典

如上所述,Python 字典(或子类 其中)被自动转换为 JSON 字符串并返回 将 Content-Type 标头设置为 application/json 的浏览器。 这使得实现基于 json 的 API 变得容易。其他数据格式 也支持 json。见教程输出过滤器学习 更多。

http://bottlepy.org/docs/dev/tutorial.html?highlight=json#generating-content

【讨论】:

  • 我正在返回一个字典,而 Bottle 返回一个错误:不支持的响应类型: 另外,从@route 返回一个字符串也没有区别。
  • 你设置内容类型了吗?
  • 有一个错误——设置内容类型只是将错误 HTML 打印为纯文本。问题是我在 Mongo 中使用地理空间。瓶子文档没有涵盖这一点。
猜你喜欢
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 2015-05-17
  • 2016-02-23
  • 2022-10-05
  • 2022-08-10
  • 2016-12-05
  • 1970-01-01
相关资源
最近更新 更多