2017-02-23 26 views
0

我有兩個腳本schema.pyload_data.py。在schema.py中,我使用sqlAlchemy Base爲超過20個表定義了模式。表中的兩個樣子:如何使用sqlAlchemy table shema加載數據

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) 

我想用我的load_data.py那些〜20桌從一個數據庫複製到另一個。我的問題是如何使用我在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

相關問題