Flask 并使用日期时间处理 Zeep 响应

Flask and handeling a Zeep response with datetime

我正在使用 Zeep, and it returns a JSON-like response with a datetime object. I want to write a micro-service using Flask 和 return 正确的 JSON 响应调用 SOAP WebService。然而,Flask 抱怨说:

TypeError: Object of type datetime is not JSON serializable
from flask import Flask
from flask_restful import Resource, Api
import datetime

app = Flask(__name__)
api = Api(app)

class foo(Resource):
    def get(self, x):
        zeepResponse = {
            'Response': {
                'Number': x,
                'DateTime': datetime.datetime(2020, 1, 1, 0, 0, 0),
                'Other': None
            }
        }
        return zeepResponse

api.add_resource(foo, '/post/<int:x>')

if __name__ == '__main__':
    app.run(debug=True)

要从命令行进行测试,只需 运行:

% curl http://localhost:5000/post/911

你能指导我如何将 zeepResponse(特别是 datetime)转换为适当的 JSON 可序列化结构吗?

调用 json.dumps(zeepResponse, default=str) 似乎解决了我的问题。来自 Stack Overflow 11875770

from flask import Flask
from flask_restful import Resource, Api
import datetime
import json

app = Flask(__name__)
api = Api(app)

class foo(Resource):
    def get(self, x):
        zeepResponse = {
            'Response': {
                'Number': x,
                'DateTime': datetime.datetime(2020, 1, 1, 0, 0, 0),
                'Other': None
            }
        }
        return json.loads(json.dumps(zeepResponse, default=str))

api.add_resource(foo, '/post/<int:x>')

if __name__ == '__main__':
    app.run(debug=True)