开发者

Bottle and Json

How do I go about returning json data from a bottle request handler. I see a dict2json method in the bottle src but I am not sure how to use it.

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.

Even dictionaries are allowed. They are converted to json and returned with Content-Type header set to application/json. To disable this feature (and pass dicts to your middleware) you can set bottle.default_app().autojson to 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


For some reason, bottle's auto-json feature doesn't work for me. 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. Have you imported 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

from bottle import request

json_data = request.json # json_data is in the dictionary format
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜