使用sqlalchemy读取整个数据库并转储为JSON

时间:2017-11-15 12:49:04

标签: python json sqlalchemy

Django具有方便manage.py命令dumpdata which can be configured to dump an entire database as JSON

目前我仅限于使用sqlalchemy而且我想做同样的事情:

将输入连接字符串视为'mysql+pymysql://user:pwd@localhost:3306/'将数据库内容设为JSON (我不需要全部Django提供的元信息,但我不介意。)

found this question详细说明了如何将SQLAlchemy对象转储为JSON,以及this from the sqlalchemy documentation概述了如何从数据库中获取所有表名:

meta = MetaData()
input_db = f'sqlite:///tmpsqlite'
engine = create_engine(input_db)
meta.reflect(bind=engine)
print(meta.tables)

如何检索这些表的所有内容,然后将其转换为JSONsqlalchemy中是否有类似于django的dumpdata功能的内置命令?

1 个答案:

答案 0 :(得分:1)

将我的解决方案留给后人:

import json

def dump_sqlalchemy(output_connection_string,output_schema):
    """ Returns the entire content of a database as lists of dicts"""
    engine = create_engine(f'{output_connection_string}{output_schema}')
    meta = MetaData()
    meta.reflect(bind=engine)  # http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html
    result = {}
    for table in meta.sorted_tables:
        result[table.name] = [dict(row) for row in engine.execute(table.select())]
    return json.dumps(result)