Is it possible to store the alembic connect string outside of alembic.ini?

后端 未结 10 1598
[愿得一人]
[愿得一人] 2021-01-30 15:41

I\'m using Alembic with SQL Alchemy. With SQL Alchemy, I tend to follow a pattern where I don\'t store the connect string with the versioned code. Instead I have file secr

10条回答
  •  北海茫月
    2021-01-30 16:31

    Alembic documentation suggests using create_engine with the database URL (instead of modifying sqlalchemy.url in code).

    Also you should modify run_migrations_offline to use the new URL. Allan Simon has an example on his blog, but in summary, modify env.py to:

    1. Provide a shared function to get the URL somehow (here it comes from the command line):

      def get_url():
          url = context.get_x_argument(as_dictionary=True).get('url')
          assert url, "Database URL must be specified on command line with -x url="
          return url
      
    2. Use the URL in offline mode:

      def run_migrations_offline():
          ...
          url = get_url()
          context.configure(
              url=url, target_metadata=target_metadata, literal_binds=True)
          ...
      
    3. Use the URL in online mode by using create_engine instead of engine_from_config:

      def run_migrations_online():
          ...
          connectable = create_engine(get_url())
          with connectable.connect() as connection:
          ...
      

提交回复
热议问题