我如何从瓶请求处理程序中返回JSON数据。我在SRC瓶中看到了DICT2JSON方法,但我不确定如何使用它。

文档中有什么:

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

当我提出页面时,给我这个:

<html>
    <head></head>
    <body>statusservertime</body>
</html>
有帮助吗?

解决方案

只需返回一个命令即可。瓶为您处理转换为JSON。

甚至允许词典。它们被转换为JSON,并将内容类型标头返回到Application/JSON。要禁用此功能(并将dicts传递给您的中间件),您可以将botter.default_app()。autojson设置为false。

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

取自 文档。

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

其他提示

由于某种原因,Bottle的自动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

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)

尝试这应该按预期工作

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)

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

from bottle import request

json_data = request.json # json_data is in the dictionary format
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top