2017-11-15 4 views
-1

Djangoは便利なmanage.pyコマンドdumpdatawhich can be configured to dump an entire database as JSONを持っています。入力'mysql+pymysql://user:[email protected]:3306/'のような接続文字列JSON(Iとして、データベースの内容を取得するようデータベース全体をsqlalchemyで読み込み、JSONとしてダンプします

テイク:現時点では

私はsqlalchemyを使用して、私は同じことをやってみたいに限定していますDjangoが提供するすべてのメタ情報を必要としませんが、気にしません)。データベースからすべてのテーブル名を取得する方法を概説JSONにSQLAlchemyのオブジェクトをダンプする方法を工夫する

I found this questionthis from the sqlalchemy documentation

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

どのように私はこれらのテーブルの内容をすべて取得しますし、その後JSONに変換します? djangoのdumpdata機能に似た組み込みコマンドがsqlalchemyにありますか?

答えて

0

後世のためにここに私の解決策を残す: `ジッパー(...)は`冗長であることを

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) 
+1

注意。 ['RowProxy'](http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.RowProxy)はそれ自身のマッピングであり、単純に' dict ) 'コンストラクタ:' dict(row) '。 –

+0

'dict()'に行のプロキシオブジェクトを渡すと、あなたは何を得ますか? –

関連する問題