Using a custom JSON encoder for SQLAlchemy's PostgreSQL JSONB implementation

前端 未结 4 1691
遥遥无期
遥遥无期 2020-12-17 17:24

I am using SQLAlchemy\'s core library to access some PostgreSQL database. Consider I have the following table:

create table foo (j jsonb);

4条回答
  •  眼角桃花
    2020-12-17 17:54

    If you're using Flask, you already have an extended JSONEncoder defined in flask.json which handles UUID, but not Decimal. It can be mapped into the SqlAlchemy engine with the json_serializer param as in @univerio's answer:

    from flask import json
    
    engine = create_engine(
        app.config['SQLALCHEMY_DATABASE_URI'],
        convert_unicode=True,
        json_serializer=json.dumps,
    )
    

    You can further extend the Flask JSONEncoder to support decimal.Decimal with the following:

    import decimal
    
    from flask import json
    
    class CustomJSONEncoder(json.JSONEncoder):
        """
        Override Flask's JSONEncoder with the single method `default`, which 
        is called when the encoder doesn't know how to encode a specific type.
        """
        def default(self, obj):
            if type(obj) is decimal.Decimal:
                return str(obj)
            else:
                # raises TypeError: obj not JSON serializable
                return json.JSONEncoder.default(self, obj)
    
    def init_json(app):
        """
        Use custom JSON encoder with Flask
        """
        app.json_encoder = CustomJSONEncoder
    

提交回复
热议问题