6
@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 として返すことができるので、mongo からその情報を取得するにはどうすればよいですか?

4

3 に答える 3

3

Python リストを返そうとしたときに、このエラーが発生しました。JSON に変換されると思っていましたが、そうではありませんでした。iterables を処理する bottle.py の行に到達し、リストの最初の dict を見つけて、上記のエラーをスローしました。

これを回避するために、リストを dict 内に埋め込んだだけです。

return {'response': []}
于 2015-05-15T03:43:18.553 に答える
2

完全な解決策は、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
        ]
    }
]
于 2012-02-23T23:09:35.173 に答える
1

ボトルhttp://bottlepy.org/docs/dev/@routeのドキュメントに記載されているように、デコレータから文字列を返す必要があります。データまたは文字列を含むテンプレートを返す必要があります。

jsonを生成する場合は、を変更する必要がありContent-Typeます。

辞書

上記のように、Pythonディクショナリ(またはそのサブクラス)は自動的にJSON文字列に変換され、Content-Typeヘッダーがapplication/jsonに設定された状態でブラウザーに返されます。これにより、jsonベースのAPIを簡単に実装できます。json以外のデータ形式もサポートされています。詳細については、tutorial-output-filterを参照してください。

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

于 2012-02-20T09:11:55.263 に答える