瓶子和杰森

时间:2010-08-17 20:33:48

标签: python json bottle

如何从瓶子请求处理程序返回json数据。我在瓶子src中看到了一个dict2json方法,但我不知道如何使用它。

文档中包含的内容:

@route('/spam')
def spam():
    return {'status':'online', 'servertime':time.time()}

当我打开页面时给我这个:

<html>
    <head></head>
    <body>statusservertime</body>
</html>

5 个答案:

答案 0 :(得分:44)

简单地返回一个词典。 Bottle为您处理转换为JSON。

  

即使是字典也是允许的。它们被转换为json并返回Content-Type标头设置为application / json。要禁用此功能(并将dicts传递给中间件),您可以将bottle.default_app()。autojson设置为False。

@route('/api/status')
def api_status():
    return {'status':'online', 'servertime':time.time()}

取自the documentation.

http://bottlepy.org/docs/stable/api.html#the-bottle-class

答案 1 :(得分:6)

出于某种原因,瓶子的auto-json功能对我不起作用。如果它也不适合你,你可以使用这个装饰器:

def json_result(f):
    def g(*a, **k):
        return json.dumps(f(*a, **k))
    return g

也很方便:

def mime(mime_type):
    def decorator(f):
        def g(*a, **k):
            response.content_type = mime_type
            return f(*a, **k)
        return g
    return decorator

答案 2 :(得分:3)

return {'status':'online', 'servertime':time.time()}非常适合我。您导入了time吗?

这有效:

import time
from bottle import route, run

@route('/')
def index():
    return {'status':'online', 'servertime':time.time()}

run(host='localhost', port=8080)

答案 3 :(得分:0)

尝试这应该按预期工作

from bson.json_util import dumps
from bottle import route, run
import time

@route('/')
def index():
     return {'status':'online', 'servertime':dumps(time.time()) }

run(host='localhost', port=8080)

答案 4 :(得分:0)

使用瓶子的请求模块很容易获得json

from bottle import request

json_data = request.json # json_data is in the dictionary format