python - 使用 Bottle 的自定义插件将日期时间作为 JSON 返回?

标签 python json serialization bottle python-datetime

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

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

最佳答案

找出这个非常简单的解决方案,即 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)))

关于python - 使用 Bottle 的自定义插件将日期时间作为 JSON 返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17798183/

相关文章:

javascript - 无法在 npm run build 上缩小代码

android - 仅在 Android 3.0 上异常(exception)

java - 将对象转换为 int 时出错

ios - 在将数组发送到 API 端点之前序列化数组

python - 如何使用 IPython 的系统 shell 配置文件作为默认 shell(Windows 7 64 位)

python - Django:在管理界面中使用 TinyMCE 4

ios - API 不包含某些对象的任何值,Xcode 在运行该应用程序时会出现 fatal error

python - Numpy 中 zeros 函数的性能

python - 将图像设置为单选按钮 - 防止垃圾收集器删除图像引用

javascript - Sails.js JSON 到 Ember