[英]Bottle and Json
如何从瓶子请求处理程序返回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()}
取自文档。
出于某种原因,瓶子的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.