Python/Batch/MongoDB:不支持的响应类型:<;类型';dict'&燃气轮机;

Python/Batch/MongoDB:不支持的响应类型:<;类型';dict'&燃气轮机;,python,pymongo,bottle,Python,Pymongo,Bottle,上述代码部分的响应为: @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 错误500

上述代码部分的响应为:

@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
错误500:内部服务器错误
抱歉,请求的URL为“”http://localhost:8080/locations'导致错误:
不支持的响应类型:

我如何从mongo中获取信息,因为瓶子可以作为JSON返回?

根据瓶子上的文档,您必须从
@route
装饰器返回字符串。您必须返回带有数据或字符串的模板

如果要生成json,则必须更改
内容类型

字典

如上所述,Python字典(或子类 自动转换为JSON字符串并返回 将内容类型标题设置为application/json的浏览器。 这使得实现基于json的API变得容易。数据格式其他 此外,还支持json。请参见教程输出过滤器以了解 更多


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

Error 500: Internal Server Error

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

Unsupported response type: <type 'dict'>
在我的情况下,生成以下内容:

@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)

当我试图返回python列表时,出现了这个错误。我以为它会翻译成JSON,但事实并非如此。它到达了瓶子.py中处理iterables的那一行,找到了列表中的第一个dict,并抛出了上面的错误

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

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

我正在返回一个字典,瓶子返回一个错误:不支持的响应类型:另外,从@route返回字符串也没有什么区别。是否设置了内容类型?设置内容类型时出错,只是将错误HTML打印为纯文本。问题是我在Mongo上使用geospatial。瓶子文档没有涵盖这一点。您是否尝试过分解问题,即用简单的字典文本替换
db.find
调用?如果它是这样工作的,那么问题一定与Mongo有关。是不是,它和瓶子有关。@Helgi我有,瓶子当然和一个普通的字典文字一起工作。但它无法处理MongoDB ObjectId。这帮了大忙。我遇到了一个类似的问题,但也有一些问题,因为我不知道MongoEncoder来自哪里。简单地返回条目对我来说是个好办法。这是故意的。有关更多信息,请参见此问题和答案:
return {'response': []}