使用Bottle创建自定义插件返回JSON格式的日期时间?

2024-09-29 19:28:00 发布

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

我不熟悉正确的瓶子语法,因此留下了以下错误:

TypeError: call() takes exactly 3 arguments (1 given)

以下是我的尝试:

from bottle import Bottle, JSONPlugin, app, route, run, static_file
from json import JSONEncoder, dumps as jsonify
from datetime import datetime


# http://bottlepy.org/docs/dev/recipes.html#ignore-trailing-slashes
class StripPathMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, e, h):
        e['PATH_INFO'] = e['PATH_INFO'].rstrip('/')
        return self.app(e, h)


# https://github.com/defnull/bottle/issues/287
class MyJsonEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return str(obj.strftime("%Y-%m-%d %H:%M:%S"))
        return JSONEncoder.default(self, obj)


@route('/api')
def latest_api_version():
    return {'api_version': 0.1, 'latest_as_of': datetime.utcnow()}


if __name__ == '__main__':
    myApp = Bottle(autojson=False)
    myApp.install(JSONPlugin(json_dumps=lambda s: jsonify(s, cls=MyJsonEncoder)))

    run(app=StripPathMiddleware(myApp()), debug=True)

如何让Bottle的JSON解析器无误地返回datetime时间戳数据?在


Tags: fromimportselfapiobjappbottledatetime
1条回答
网友
1楼 · 发布于 2024-09-29 19:28:00

在bugtracker中找到了一个非常简单的解决方案also mentioned

from bottle import install, JSONPlugin

...

if __name__ == '__main__':
    app = Bottle(autojson=False)
    app.install(JSONPlugin(json_dumps=lambda s: jsonify(s, cls=MyJsonEncoder)))

相关问题 更多 >

    热门问题