[英]Bottle and Json
How do I go about returning json data from a bottle request handler. 如何从瓶子请求处理程序返回json数据。 I see a dict2json method in the bottle src but I am not sure how to use it.
我在瓶子src中看到了一个dict2json方法,但我不知道如何使用它。
What is in the documentation: 文档中包含的内容:
@route('/spam')
def spam():
return {'status':'online', 'servertime':time.time()}
Gives me this when I bring up the page: 当我打开页面时给我这个:
<html>
<head></head>
<body>statusservertime</body>
</html>
Simply return a dict. 只需返回一个字典。 Bottle handles the conversion to JSON for you.
Bottle为您处理转换为JSON。
Even dictionaries are allowed.
甚至允许使用词典。 They are converted to json and returned with Content-Type header set to application/json.
它们被转换为json并返回Content-Type标头设置为application / json。 To disable this feature (and pass dicts to your middleware) you can set bottle.default_app().autojson to False.
要禁用此功能(并将dicts传递给中间件),您可以将bottle.default_app()。autojson设置为False。
@route('/api/status')
def api_status():
return {'status':'online', 'servertime':time.time()}
Taken from the documentation. 取自文档。
http://bottlepy.org/docs/stable/api.html#the-bottle-class http://bottlepy.org/docs/stable/api.html#the-bottle-class
For some reason, bottle's auto-json feature doesn't work for me. 出于某种原因,瓶子的auto-json功能对我不起作用。 If it doesn't work for you either, you can use this decorator:
如果它也不适合你,你可以使用这个装饰:
def json_result(f):
def g(*a, **k):
return json.dumps(f(*a, **k))
return g
Also handy: 也方便:
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()}
works perfectly well for me. return {'status':'online', 'servertime':time.time()}
非常适合我。 Have you imported time
? 你有进口
time
吗?
This works: 这有效:
import time
from bottle import route, run
@route('/')
def index():
return {'status':'online', 'servertime':time.time()}
run(host='localhost', port=8080)
try this should works as intended 试试这应该按预期工作
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)
it is easy to get json using bottle's request module 使用瓶子的请求模块很容易得到json
from bottle import request
json_data = request.json # json_data is in the dictionary format
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.