在将 sqlalchemy 映射设置到 python 中的 sqlite 数据库时,我有一个关于“安排代码,这取决于彼此”的小问题。
目标是编写一个脚本,它满足以下条件:
- 获取一个
filename
参数作为命令行参数。 - 基于
filename
它应该创建一个 SQLite 数据库的绝对路径。 - 它应该连接到数据库并创建一个
engine
- 它应反映该数据库中的表。
- 它应该将表中
monkey patch
的列作为主键列,因为该表没有主键并且 sqlalchemy 需要一个。id
mytable
所以我想出了这个:
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
def create_path(file_name):
# generate absolute path to file_name
path_to_file = create_path("my_file_name.sqlite")
engine = create_engine('sqlite:///{path}'.format(path=path_to_file), echo=False)
Base = declarative_base()
Base.metadata.create_all(engine)
class MyTable(Base):
__tablename__ = 'my_table'
__table_args__ = {'autoload': True}
id = Column(Integer, primary_key=True) # Monkey patching the id column as primary key.
def main(argv):
# parse file_name here from argv
Session = sessionmaker(bind=engine)
session = Session()
for row in session.query(MyTable).all():
print row
return "Stop!"
if __name__ == '__main__':
sys.exit(main())
But this is a doomed construction and I don't see how I could rearrange my code without breaking the dependencies.
- To be able to create
MyClass
I needBase
to be defined beforeMyClass
. - To be able to create
Base
I needengine
to be defined beforeBase
. - To be able to create
engine
I needpath_to_file
to be defined beforeengine
. - To be able to create
path_to_file
outside ofmain()
I needcreate_file()
to be defined beforepath_to_file
. - And so on...
Hopefully you see where I am stuck...
Any suggestions?
Edit: By the way, the code works, but only with a hardcoded filename in the top of the script.