24

I tried to change in Alembic but when I try to run Alembic current I got error. I'm new in alembic, please tell me why I get this error and how can I solve it?

I can see alembic.ini in migration folder and also revision identifiers, used by Alembic and everything seems fine.

$alembic current
No handlers could be found for logger "alembic.util"
  FAILED: No config file 'alembic.ini' found, or file has no '[alembic]' section

20c921506336_.py:

"""empty message

Revision ID: 20c921506336
Revises: None
Create Date: 2015-01-30 16:28:38.981023

"""

# revision identifiers, used by Alembic.
revision = '20c921506336'
down_revision = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('user',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=50), nullable=True),
    sa.Column('email', sa.String(length=50), nullable=True),
    sa.Column('age', sa.Integer(), nullable=True),
    sa.Column('bestfriend_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['bestfriend_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(u'ix_user_age', 'user', ['age'], unique=True)
    op.create_index(u'ix_user_email', 'user', ['email'], unique=True)
    op.create_index(u'ix_user_name', 'user', ['name'], unique=True)
    op.create_table('friends',
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('friend_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['friend_id'], ['user.id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], )
    )
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('friends')
    op.drop_index(u'ix_user_name', table_name='user')
    op.drop_index(u'ix_user_email', table_name='user')
    op.drop_index(u'ix_user_age', table_name='user')
    op.drop_table('user')
    ### end Alembic commands ###
1
  • 1
    Was this ever solved? Neither of these answers work for me.
    – Mote Zart
    Sep 26, 2019 at 3:28

4 Answers 4

23

You must cd to the directory that has the alembic.ini to run the alembic command, that is, the alembic.ini must be found in the current working directory; or you can specify the config file location with alembic -c path/to/alembic.ini.

And it seems that your alembic ini is broken, you ought to have script_location in there, thus if your migrations are in the alembic subdirectory, alembic.ini should read something like:

[alembic]
script_location = alembic

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

The directory layout must be so that if your script_location = alembic it means that you have:

alembic.ini
alembic/   # this must match the script_location in alembic.ini
    env.py   # and this must be found at the script_location
    script.py.mako
    versions/
        20c921506336_.py
2
  • I did it but got this (venv)peg@peg:~/flask-Alembic/migrations$ alembic current No handlers could be found for logger "alembic.util" FAILED: No 'script_location' key found in configuration. @Antti Haapala
    – Linda
    Feb 8, 2015 at 9:21
  • its the same in mine too so I have it the exact same @Antti Haapala
    – Linda
    Feb 8, 2015 at 9:25
21

For a deploy script doing something like this:

ssh ... alembic upgrade head

Antii's answer provides the direct answer which is the -c option:

ssh ... alembic -c /path/to/alembic.ini upgrade head

However then you may get like me:

FAILED: Path doesn't exist: 'alembic'. Please use the 'init' command to create a new scripts folder.

Alembic is failing to interpret your intention for script_location in alembic.ini. Usually you run alembic from the directory with alembic.ini and alembic is able to interpret your script_location as a relative path.

However when you run it with a simple deploy script or otherwise from a different directory, it doesn't know where to look and it does not use the directory of alembic.ini to guess the location (as I think Antii suggested?).

If you look in the alembic source code here, you can see that alembic wants either 1) an absolute path, 2) a package path or 3) a relative path from the working directory (the default case).

Therefore the second level of this answer is

Option 1: Absolute path

(I haven't tested this!) Provide an absolute path to the alembic directory in alembic.ini. This doesn't work for me because the code becomes unportable:

...
script_location = /path/to/alembic/
...

Option 2: Package path

Provide a package path in alembic.ini:

...
script_location = rootpackage:alembic  # or maybe rootpacakge.xyz:alembic
...

and of course it will actually need to be a package so the location with alembic.ini must have __init__.py.

Option 3: Relative path

Instead of running alembic upgrade directly in your deploy script, make a bash script to cd to the right directory and then run it.

2
  • 2
    great answer. for the relative path issue use docker or another virtual env solution for cross-machine portability.
    – aaron
    Dec 8, 2020 at 20:18
  • 1
    7 years later, Thank you!
    – rumbarum
    Jun 30 at 4:23
0

I have same problem, my alembic.ini file was in root project folder. And look like this

[alembic]
script_location = alembic
file_template = %%(year)d-%%(month).2d-%%(day)-2dT%%(hour).2d-%%(minute).2d-%%(second).2d_%%(rev)s
prepend_sys_path = .
version_path_separator = os
sqlalchemy.url = postgresql://%(POSTGRES_USER)s:%(POSTGRES_PASSWORD)s@%(POSTGRES_HOST)s:%(POSTGRES_PORT)s/%(POSTGRES_DB)s

But when i run my pytest they was in tests filder and alembic try to find filder there. And after it raise exc. So i see two solution, create separate alembic_pytest.ini file. Or make some magic.

And i write fixture for migration.

ALEMBIC_INI_PATH = (Path(__file__).parent.parent / "alembic.ini").resolve()


@pytest.fixture
def migrated_postgres():
    al_config = AlembicConfig(ALEMBIC_INI_PATH)
    script_location = al_config.get_main_option("script_location")
    al_config.set_main_option("script_location", f"../{script_location}")
    with temp_db(conf.db_url) as db_url:
        alembic.command.upgrade(al_config, "head")
        yield db_url

As you se a get script_location field and modified it for parent folder. It is not so perfect solution, but it work

P.S. I wish to have multiply path in script_location for situation like this

0

You can set the default working directory for pytest to a specific value, meaning it will not change.

Click Edit Configuration:

enter image description here

then Edit configuration templates...:

enter image description here

From Python Tests select pytest:

enter image description here

and set your default Working Directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.