SQLAlchemy JSON as blob/text

后端 未结 8 1902
猫巷女王i
猫巷女王i 2020-12-02 13:42

I\'m storing JSON down as blob/text in a column using MySQL. Is there a simple way to convert this into a dict using python/SQLAlchemy?

8条回答
  •  醉梦人生
    2020-12-02 14:21

    There is a recipe for this in the official documentation:

    from sqlalchemy.types import TypeDecorator, VARCHAR
    import json
    
    class JSONEncodedDict(TypeDecorator):
        """Represents an immutable structure as a json-encoded string.
    
        Usage::
    
            JSONEncodedDict(255)
    
        """
    
        impl = VARCHAR
    
        def process_bind_param(self, value, dialect):
            if value is not None:
                value = json.dumps(value)
    
            return value
    
        def process_result_value(self, value, dialect):
            if value is not None:
                value = json.loads(value)
            return value
    

提交回复
热议问题