2012-02-20 39 views
5
@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 

對於上面的代碼部分的響應是:的Python /瓶/ MongoDB的:不支持的響應類型:<type 'dict'>

Error 500: Internal Server Error 

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

Unsupported response type: <type 'dict'> 

我怎樣才能抓住,作爲一種類型的瓶從蒙戈信息可以返回作爲JSON ?

+0

您是否嘗試過分解問題,即用簡單的字典文字替換'db.find'調用?如果這樣工作,問題必須與Mongo相關。它不是,它與瓶子有關。 – Helgi 2012-02-23 14:35:19

+0

@Helgi我有,瓶當然與常規字典文字工作。但它不能處理MongoDB ObjectId。 – 2012-02-23 22:46:59

回答

2

完整的解決方案是將所述分貝光標移動到列表中,手動設置響應類型+定製編碼的返回值

@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.0000006, 
      -117.19483074631853 
     ] 
    }, 
    { 
     "_id": "4f4201587e720d1dca000002", 
     "coordinate2d": [ 
      33.158092999999994, 
      -117.350594 
     ] 
    }, 
    { 
     "_id": "4f42018b7e720d1dca000003", 
     "coordinate2d": [ 
      33.195870000000006, 
      -117.379483 
     ] 
    } 
] 
+0

這非常有幫助。我遇到了類似的問題,但由於我不知道MongoEncoder來自哪裏,因此遇到了問題。 **簡單地返回條目爲我做了訣竅。** – Hectron 2013-06-05 20:57:11

1

根據瓶子http://bottlepy.org/docs/dev/上的文檔提及,您必須從@route裝飾器中返回字符串。您必須使用數據或字符串返回模板。

如果要生成json,則必須更改Content-Type

Dictionaries

As mentioned above, Python dictionaries (or subclasses thereof) are automatically transformed into JSON strings and returned to the browser with the Content-Type header set to application/json. This makes it easy to implement json-based APIs. Data formats other than json are supported too. See the tutorial-output-filter to learn more.

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

+0

我正在返回一本字典,Bottle返回錯誤: 不支持的響應類型: 另外,從@route返回字符串沒有區別。 – 2012-02-21 12:12:31

+0

你有沒有設置內容類型? – Nilesh 2012-02-21 12:36:26

+0

發生錯誤 - 設置內容類型僅僅以純文本格式輸出錯誤HTML。問題是我在Mongo中使用地理空間。瓶子文檔不包括這些。 – 2012-02-21 12:38:33

0

我得到這個錯誤,當我tr ying返回一個python列表。我認爲它會轉化爲JSON,但事實並非如此。它將它放在bottle.py中處理iterables的行中,並找到列表中的第一個字典,並拋出上面的錯誤。

爲了解決這個問題,我簡單地將我的列表嵌入字典。

return {'response': []} 
+0

這是故意的。看到這個問題和答案更多信息:http://stackoverflow.com/questions/12293979/how-do-i-return-a-json-array-with-bottle – Peter 2017-04-13 08:47:50

相關問題