【问题标题】:Custom plugin with Bottle to return datetime as JSON?带有Bottle的自定义插件以将日期时间返回为JSON?
【发布时间】:2023-04-08 06:04:01
【问题描述】:

我不熟悉正确的 Bottle 语法,因此我留下了这个错误:

TypeError: call() 只需要 3 个参数(给定 1 个)

这是我的尝试:

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 解析器正确返回日期时间时间戳数据?

【问题讨论】:

  • 请发布完整的回溯。给我们十几行代码并告诉我们其中某处有错误不会让你走得太远。这种错误实际上是回溯中最不有用的部分

标签: python json serialization bottle python-datetime


【解决方案1】:

在 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)))

【讨论】:

    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2015-09-30
    • 2016-12-29
    相关资源
    最近更新 更多