【问题标题】:Read entire database with sqlalchemy and dump as JSON使用 sqlalchemy 读取整个数据库并将其转储为 JSON
【发布时间】:2017-11-15 23:12:53
【问题描述】:

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功能的内置命令?

【问题讨论】:

    标签: python json sqlalchemy


    【解决方案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)
    

    【讨论】:

    • 请注意,zip(...) 是多余的。 RowProxy 本身就是一个映射,您可以简单地将其传递给 dict() 构造函数:dict(row)
    • 如果你传递 dict() 一个行代理对象,你会得到什么。
    • sqlalchemy 需要的导入是from sqlalchemy import create_engine; from sqlalchemy.schema import MetaData
    猜你喜欢
    • 2023-04-08
    • 2014-10-29
    • 2020-12-02
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多