sqlalchemy自定义压缩字段

有时候我们需要存储较大json至mysql字段中,即使是text类型 也会有字段超出情况,那我们就得想办法进行字段压缩存储。

 

同时保证数据在读取后,不需要做额外工作。

 

#coding=utf-8
from io import BytesIO
from gzip import GzipFile
import jsonpickle
import sqlalchemy.types as types

def compress_string(s):
    zbuf = BytesIO()
    with GzipFile(mode='wb', compresslevel=6, fileobj=zbuf, mtime=0) as zfile:
        zfile.write(s)
    return zbuf.getvalue()

def uncompress_string(s):
    """helper function to reverse text.compress_string"""
    import base64
    import io
    import gzip
    try:
        val = base64.b64decode(s)
        zbuf = BytesIO(val)
        zfile = gzip.GzipFile(fileobj=zbuf)
        ret = zfile.read()
        zfile.close()
    except Exception as e:
        print(e)
        ret = s
    return ret


class CompressField(types.TypeDecorator):
    impl = types.Unicode
    def process_bind_param(self, value, engine):
        import base64
        if value:
            value = value.encode('utf8')
            value = compress_string(value)
            value = base64.b64encode(value).decode('utf8')
        return value
        # return unicode(jsonpickle.encode(value))

    def process_result_value(self, value, engine):
        if value:
            # return jsonpickle.decode(value)
            return uncompress_string(value).decode('utf8')
        else:
            # default can also be a list
            return '[]'

 

压缩代码我们copy django 

compress_string 方法。

 

以上我们就满足了sqlalchemy自定义压缩字段。

有一个不好的地方就是在数据库中 无法直接查询json内容, 必须基于sqlalchemy进行查询。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yinxingpan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值