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 answer to the above part of the code:
Error 500: Internal Server Error
Sorry, the requested URL 'http://localhost:8080/locations' caused an error:
Unsupported response type: <type 'dict'>
How can I get this information from mongo as a type Bottle can be returned as JSON?
The complete solution was a combination of converting the db cursor to a list, manually setting the response type + custom encoding of 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, this is:
[
{
"_id": "4f4201bb7e720d1dca000005",
"coordinate2d": [
33.02032100000006,
-117.19483074631853
]
},
{
"_id": "4f4201587e720d1dca000002",
"coordinate2d": [
33.158092999999994,
-117.350594
]
},
{
"_id": "4f42018b7e720d1dca000003",
"coordinate2d": [
33.195870000000006,
-117.379483
]
}
]
According to the mention of the document on the bottle http://bottlepy.org/docs/dev/ you need to return the line from the decorator @route. You must return a template with data or a string.
If you want to generate json, you need to change Content-Type.
Dictionaries
, Python ( ) JSON Content-Type, application/json. json-based API. json. --, .
http://bottlepy.org/docs/dev/tutorial.html?highlight=json#generating-content
I got this error when trying to return a python list. I assumed that this would translate to JSON, but it is not. He did this on a line in bottle.py where he would handle the iterations and find the first dict in the list and make the error above.
To get around this, I simply included my list inside the dict.
return {'response': []}