views:

72

answers:

3

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>
+3  A: 

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.

Andrew
A: 

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)
Tim McNamara
A: 

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
David M.