<p>以下是我在将软件连接到<code>alembic</code>后学到的内容:</p>
<h2>有没有办法从我的Python代码中调用alembic?</h2>
<p>是的。在撰写本文时,alembic的主要入口点是<a href="https://github.com/zzzeek/alembic/blob/0e3319bb36f1612e41a8d7da5a48ce1ca33a0b2b/alembic/config.py#L476" rel="noreferrer">^{<cd2>}</a>,因此您可以导入它并自己调用它,例如:</p>
<pre><code>import alembic.config
alembicArgs = [
'--raiseerr',
'upgrade', 'head',
]
alembic.config.main(argv=alembicArgs)
</code></pre>
<p>注意,alembic在当前目录(即os.getcwd())中查找迁移。在调用alembic之前,我已经通过使用<code>os.chdir(migration_directory)</code>处理了这个问题,但是可能有更好的解决方案。</p>
<hr/>
<h2>我可以在不编辑.ini文件的情况下从命令行指定新的数据库位置吗?</h2>
<p>是的。关键在于<code>-x</code>命令行参数。从<code>alembic -h</code>(令人惊讶的是,我在文档中找不到命令行参数引用):</p>
<pre><code>optional arguments:
-x X Additional arguments consumed by custom env.py
scripts, e.g. -x setting1=somesetting -x
setting2=somesetting
</code></pre>
<p>因此,您可以创建自己的参数,例如<code>dbPath</code>,然后在<code>env.py</code>中截取它:</p>
<p><code>alembic -x dbPath=/path/to/sqlite.db upgrade head</code></p>
<p>例如在<code>env.py</code>中:</p>
<pre><code>def run_migrations_online():
# get the alembic section of the config file
ini_section = config.get_section(config.config_ini_section)
# if a database path was provided, override the one in alembic.ini
db_path = context.get_x_argument(as_dictionary=True).get('dbPath')
if db_path:
ini_section['sqlalchemy.url'] = db_path
# establish a connectable object as normal
connectable = engine_from_config(
ini_section,
prefix='sqlalchemy.',
poolclass=pool.NullPool)
# etc
</code></pre>
<p>当然,您也可以在<code>alembic.config.main</code>中使用<code>argv</code>来提供-x参数。</p>
<p>我同意<a href="https://stackoverflow.com/a/24623004/1286571">@davidism</a>关于使用迁移vs<code>metadata.create_all()</code>:)</p>