SQLAlchemy JSON 作为 blob/文本 [英] SQLAlchemy JSON as blob/text

查看:29
本文介绍了SQLAlchemy JSON 作为 blob/文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MySQL 将 JSON 以 blob/文本的形式存储在列中.有没有一种简单的方法可以使用 python/SQLAlchemy 将其转换为 dict?

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?

推荐答案

您可以非常轻松地创建您自己的类型 使用 SQLAlchemy

You can very easily create your own type with SQLAlchemy

对于 SQLAlchemy 版本 >= 0.7,请查看下面的Yogesh 的回答

For SQLAlchemy versions >= 0.7, check out Yogesh's answer below

import jsonpickle
import sqlalchemy.types as types

class JsonType(types.MutableType, types.TypeDecorator):    
    impl = types.Unicode

    def process_bind_param(self, value, engine):
        return unicode(jsonpickle.encode(value))

    def process_result_value(self, value, engine):
        if value:
            return jsonpickle.decode(value)
        else:
            # default can also be a list
            return {}

这可以在您定义表时使用(示例使用 elixir):

This can be used when you are defining your tables (example uses elixir):

from elixir import *
class MyTable(Entity):
    using_options(tablename='my_table')
    foo = Field(String, primary_key=True)
    content = Field(JsonType())
    active = Field(Boolean, default=True)

你也可以使用不同的 json 序列化器来 jsonpickle.

You can also use a different json serialiser to jsonpickle.

这篇关于SQLAlchemy JSON 作为 blob/文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆