Bottle和Json
我该如何从一个Bottle请求处理器中返回json数据呢?我在Bottle的源代码中看到了一个dict2json的方法,但我不太确定该怎么用。
文档中是这么说的:
@route('/spam')
def spam():
return {'status':'online', 'servertime':time.time()}
当我打开这个页面时,它给了我这个结果:
<html>
<head></head>
<body>statusservertime</body>
</html>
5 个回答
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)
6
出于某种原因,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
44
你只需要返回一个字典(dict)。Bottle会帮你把它转换成JSON格式。
字典也是可以的。它们会被转换成JSON格式,并且返回时会带上Content-Type头,设置为application/json。如果你想关闭这个功能(并把字典传递给你的中间件),可以把bottle.default_app().autojson设置为False。
@route('/api/status')
def api_status():
return {'status':'online', 'servertime':time.time()}
摘自 文档。