سؤال

I am unfamiliar with the correct Bottle syntax, as such I am left with this error:

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

Here is my attempt:

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)

How do I get Bottle's JSON parser to return datetime timestamp data without error?

هل كانت مفيدة؟

المحلول

Figured out this really simple solution which is also mentioned in the bugtracker:

from bottle import install, JSONPlugin

...

if __name__ == '__main__':
    app = Bottle(autojson=False)
    app.install(JSONPlugin(json_dumps=lambda s: jsonify(s, cls=MyJsonEncoder)))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top