2017-02-23 6 views
0

私は2つのスクリプトschema.pyload_data.pyを持っています。 schema.pyでは、sqlAlchemy Baseを使用して20を超えるテーブルのスキーマを定義します。テーブルの二つは、次のようになります。sqlAlchemyテーブルシーマを使用してデータをロードする方法

schema.py

Base = declarative_base() 
meta = MetaData() 

class Table1(Base): 
    __tablename__ = 'table1' 
    id = Column(Integer, primary_key=True) 
    name = Column(String) 

class Table2(Base): 
    __tablename__ = 'table2' 
    id = Column(Integer, primary_key=True) 
    bdate = Column(Date) 
... 
class Table20(Base): 
    __tablename__ = 'table20' 
    id = Column(Integer, primary_key=True) 
    bdate = Column(Date) 

私は別のデータベースからのもの〜20個のテーブルをコピーするために、私のload_data.pyを使用します。私の質問はschema.pyで定義したスキーマを使用してload_data.pyにテーブルを作成する方法です。 Introductory Tutorial of Python’s SQLAlchemyの例に続いて、importを使用してすべてのテーブルスキーマクラスを読み込みますが、それはあまりにも面倒です。この状況を処理するためのよりよい方法はありますか?私はsqlAlchemyを初めて使用しています。

load_data.py

from schema import Base, Table1, Table2, Table3, Table4, Table5, Table6, Table7, Table8, Table9, Table10,..., Table20 

src_engine = create_engine('sqlite:// sqlite_test.db') 
dst_engine = create_engine('postgresql:///postgresql_test.db') 

Base.metadata.create_all(dst_engine) 

tables = Base.metadata.tables 

for tbl in tables: 
    data = src_engine.execute(tables[tbl].select()).fetchall() 
    for a in data: print(a) 
    if data: 
     dst_engine.execute(tables[tbl].insert(), data) 

答えて

1

モジュールからすべてのメンバーをインポートfrom schema import *を、試してみてください。 import schemafrom schema import xの違いについては、these answersも参照してください。

関連する問題