Python / Bottle / MongoDB:不支持的响应类型:

前端之家收集整理的这篇文章主要介绍了Python / Bottle / MongoDB:不支持的响应类型:前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

  1. @route('/locations',method='GET')
  2. def get_location():
  3. entity = db['locations'].find({'coordinate2d': {'$near': [37.871593,-122.272747]}}).limit(3)
  4. if not entity:
  5. abort(404,'No nearby locations')
  6. return entity

上述代码部分的响应是:

  1. Error 500: Internal Server Error
  2. Sorry,the requested URL 'http://localhost:8080/locations' caused an error:
  3. Unsupported response type:

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

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

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

在我的情况下,产生这个:

  1. [
  2. {
  3. "_id": "4f4201bb7e720d1dca000005","coordinate2d": [
  4. 33.02032100000006,-117.19483074631853
  5. ]
  6. },{
  7. "_id": "4f4201587e720d1dca000002","coordinate2d": [
  8. 33.158092999999994,-117.350594
  9. ]
  10. },{
  11. "_id": "4f42018b7e720d1dca000003","coordinate2d": [
  12. 33.195870000000006,-117.379483
  13. ]
  14. }
  15. ]

猜你在找的Python相关文章