Python/Bottle/Mongodb:サポートされていない応答タイプ:<タイプ '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
コードの上記の部分の応答は次のとおりです。
Error 500: Internal Server Error
Sorry, the requested URL 'http://localhost:8080/locations' caused an error:
Unsupported response type: <type 'dict'>
タイプのボトルがJSONとして戻ることができるため、マンゴからその情報を取得するにはどうすればよいですか?
解決
完全なソリューションは、DBカーソルをリストに変換し、応答タイプ +カスタムを手動で設定してリターン値をエンコードする組み合わせでした
@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.02032100000006,
-117.19483074631853
]
},
{
"_id": "4f4201587e720d1dca000002",
"coordinate2d": [
33.158092999999994,
-117.350594
]
},
{
"_id": "4f42018b7e720d1dca000003",
"coordinate2d": [
33.195870000000006,
-117.379483
]
}
]
他のヒント
ボトルに記載されているドキュメントによると http://bottlepy.org/docs/dev/ から文字列を返す必要があります @route
デコレーター。テンプレートをデータまたは文字列で返す必要があります。
JSONを生成したい場合は、 Content-Type
.
辞書
上記のように、Python辞書(またはそのサブクラス)は自動的にJSON文字列に変換され、Application/JSONにコンテンツタイプのヘッダーセットを使用してブラウザに戻ります。これにより、JSONベースのAPIを簡単に実装できます。 JSON以外のデータ形式もサポートされています。詳細については、チュートリアルの出力フィルターをご覧ください。
http://bottlepy.org/docs/dev/tutorial.html?highlight=json#generating-content
Pythonリストを返しようとしているときにこのエラーが発生しました。私はそれがJSONに翻訳されると思いましたが、そうではありませんでした。それはbottle.pyのラインにたどり着き、そこで反復可能なものを処理し、リストの最初のdictを見つけて、上記のエラーを投げました。
これを回避するために、私は単に私のリストをdictに埋め込んだだけです。
return {'response': []}