瓶子和Json

2024-05-11 08:49:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从瓶子请求处理程序返回json数据。我在bottle src中看到一个dict2json方法,但是我不知道如何使用它。

文档中的内容:

@route('/spam')
def spam():
    return {'status':'online', 'servertime':time.time()}

当我打开页面时给我这个:

<html>
    <head></head>
    <body>statusservertime</body>
</html>

Tags: 数据方法文档srcjson处理程序瓶子bottle
3条回答

出于某种原因,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

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)

只需返回一个dict.battle就可以为您处理到JSON的转换。

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()}

取自the documentation.

http://bottlepy.org/docs/stable/api.html#the-bottle-class

相关问题 更多 >