Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Bottle/MongoDB: Unsupported response type: <type 'dict'>

@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

The response for the above portion of code is:

Error 500: Internal Server Error

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

Unsupported response type: <type 'dict'>

How can I grab that information from mongo as a type Bottle can return as JSON?

like image 589
james_womack Avatar asked Feb 20 '12 09:02

james_womack


2 Answers

I got this error when I was trying to return a python list. I assumed it would translate into JSON, but it didn't. It made it to the line in bottle.py where it would handle iterables and found the first dict in the list and threw the error above.

To get around this, I simply embedded my list inside a dict.

return {'response': []}
like image 167
Daniel Watrous Avatar answered Nov 12 '22 14:11

Daniel Watrous


The complete solution was a combination of transforming the db cursor to a list, manually setting the response type + custom encoding the return value

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

In my case, produces this:

[
    {
        "_id": "4f4201bb7e720d1dca000005",
        "coordinate2d": [
            33.02032100000006,
            -117.19483074631853
        ]
    },
    {
        "_id": "4f4201587e720d1dca000002",
        "coordinate2d": [
            33.158092999999994,
            -117.350594
        ]
    },
    {
        "_id": "4f42018b7e720d1dca000003",
        "coordinate2d": [
            33.195870000000006,
            -117.379483
        ]
    }
]
like image 2
james_womack Avatar answered Nov 12 '22 13:11

james_womack