如何从瓶子请求处理程序返回 json 数据。我在瓶子 src 中看到了一个 dict2json 方法,但我不确定如何使用它。
文档中的内容:
@route('/spam')
def spam():
return {'status':'online', 'servertime':time.time()}
当我打开页面时给我这个:
<html>
<head></head>
<body>statusservertime</body>
</html>
只需返回一个字典。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()}
取自文档。
出于某种原因,bottle 的 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
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