【问题标题】:json serialisation of dates on flask restful烧瓶restful上日期的json序列化
【发布时间】:2017-01-18 15:29:16
【问题描述】:

我有以下资源:

class Image(Resource):
    def get(self, db_name, col_name, image_id):
        col = mongo_client[db_name][col_name]
        image = col.find_one({'_id':ObjectId(image_id)})
        try:
            image['_id'] = str(image['_id'])
        except TypeError:
            return {'image': 'notFound'}
        return {'image':image}

链接到某个端点。

但是,image 内部包含某些 datetime 对象。我可以用 `json.dumps(..., default=str) 来解决这个问题,但我发现有一种方法可以在 flask-restful 上执行此操作。我只是不清楚具体需要做什么。

特别是,我读到:

    It is possible to configure how the default Flask-RESTful JSON
    representation will format JSON by providing a RESTFUL_JSON
    attribute on the application configuration. 
    This setting is a dictionary with keys that 
     correspond to the keyword arguments of json.dumps().

class MyConfig(object):
    RESTFUL_JSON = {'separators': (', ', ': '),
                    'indent': 2,
                    'cls': MyCustomEncoder}

但我不清楚这需要放在哪里。尝试了一些方法,但没有成功。

编辑:

我终于解决了这个问题:

紧接着

api = Api(app)

我补充说:

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            #return int(obj.strftime('%s'))
            return str(obj)
        elif isinstance(obj, datetime.date):
            #return int(obj.strftime('%s'))
            return str(obj)
        return json.JSONEncoder.default(self, obj)


def custom_json_output(data, code, headers=None):
    dumped = json.dumps(data, cls=CustomEncoder)
    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp

api = Api(app)
api.representations.update({
    'application/json': custom_json_output
})

【问题讨论】:

  • 你能不能直接将每个日期时间转换为image['date'] = str(image['date'])
  • 我可以,但是我必须检查每个有问题的变量,对于每个调用服务器的函数,我认为这不是很有效

标签: flask flask-restful


【解决方案1】:

刚刚清除了这一点,您只需执行以下操作:

app = Flask(__name__)
api = Api(app)
app.config['RESTFUL_JSON'] = {'cls':MyCustomEncoder}

这适用于普通 Flask 和 Flask-RESTful。

注意事项:

1) 显然文档的以下部分不是很清楚:

可以配置默认的 Flask-RESTful JSON 表示将通过提供 RESTFUL_JSON 属性来格式化 JSON 关于应用程序配置。此设置是一个字典 与 json.dumps() 的关键字参数对应的键。

class MyConfig(object):
    RESTFUL_JSON = {'separators': (', ', ': '),
                    'indent': 2,
                    'cls': MyCustomEncoder}

2)除了 'cls' 参数之外,您实际上可以覆盖 json.dumps 函数的任何关键字参数。

【讨论】:

    【解决方案2】:

    已创建 Flask 应用程序,例如像这样:

    root_app = Flask(__name__)
    

    MyConfig 放在某个模块中,例如config.py 然后配置root_app 比如:

    root_app.config.from_object('config.MyConfig')
    

    【讨论】:

    • 这似乎在选择配置文件的意义上有效,但序列化错误仍然存​​在,我使用str 代替MyCustomEncoder
    • 嗯,你的问题主要是关于如何确保应用程序尊重你的自定义配置,所以我很感激你的批准。编辑您的答案以包含堆栈跟踪,我们也可以考虑序列化错误本身:)
    • 你说得对,我设法用不同的方法让它工作,但是谢谢。
    • 谢谢!为了他人的利益 -> 你是如何解决序列化问题的?
    猜你喜欢
    • 1970-01-01
    • 2014-04-11
    • 2014-11-25
    • 2020-05-07
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    相关资源
    最近更新 更多