17
votes

I started using Flask-Migrate today and installed it on a test project. However i am getting following error:

alembic.util.exc.CommandError: Can't locate revision identified by 'e39d16e62810'

Steps to reproduce:

  1. run "python create_db.py"
  2. run "flask db init"
  3. add column "name" to Entry-model
  4. run "flask db migrate"

EDIT: After removing migrations directory and repeating the process i am getting the same error after running "flask db migrate". I also tried using a manage.py file with flask-script --> same issue

Error:

(venv_mentz) H:\Flask-API-Test>python manage.py db migrate
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
Traceback (most recent call last):
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 143, in _catch_revision_errors
    yield
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 206, in get_revisions
    return self.revision_map.get_revisions(id_)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in get_revisions
    return sum([self.get_revisions(id_elem) for id_elem in id_], ())
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in <listcomp>
    return sum([self.get_revisions(id_elem) for id_elem in id_], ())
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in get_revisions
    for rev_id in resolved_id)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in <genexpr>
    for rev_id in resolved_id)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 362, in _revision_for_ident
    resolved_id)
alembic.script.revision.ResolutionError: No such revision or branch 'e39d16e62810'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    manager.run()
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_script\__init__.py", line 417, in run
    result = self.handle(argv[0], argv[1:])
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_script\__init__.py", line 386, in handle
    res = handle(*args, **config)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_script\commands.py", line 216, in __call__
    return self.run(*args, **kwargs)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
    version_path=version_path, rev_id=rev_id)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\command.py", line 176, in revision
    script_directory.run_env()
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 425, in run_env
    util.load_python_file(self.dir, 'env.py')
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
    module = load_module_py(module_id, path)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
    spec.loader.exec_module(module)
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "migrations\env.py", line 87, in <module>
    run_migrations_online()
  File "migrations\env.py", line 80, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\runtime\environment.py", line 836, in run_migrations
    self.get_context().run_migrations(**kw)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\runtime\migration.py", line 321, in run_migrations
    for step in self._migrations_fn(heads, self):
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\command.py", line 156, in retrieve_migrations
    revision_context.run_autogenerate(rev, context)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\autogenerate\api.py", line 415, in run_autogenerate
    self._run_environment(rev, migration_context, True)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\autogenerate\api.py", line 425, in _run_environment
    if set(self.script_directory.get_revisions(rev)) != \
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 206, in get_revisions
    return self.revision_map.get_revisions(id_)
  File "c:\users\marschall\appdata\local\programs\python\python36-32\Lib\contextlib.py", line 100, in __exit__
    self.gen.throw(type, value, traceback)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 174, in _catch_revision_errors
    compat.raise_from_cause(util.CommandError(resolution))
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\compat.py", line 194, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\compat.py", line 187, in reraise
    raise value.with_traceback(tb)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 143, in _catch_revision_errors
    yield
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 206, in get_revisions
    return self.revision_map.get_revisions(id_)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in get_revisions
    return sum([self.get_revisions(id_elem) for id_elem in id_], ())
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in <listcomp>
    return sum([self.get_revisions(id_elem) for id_elem in id_], ())
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in get_revisions
    for rev_id in resolved_id)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in <genexpr>
    for rev_id in resolved_id)
  File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 362, in _revision_for_ident
    resolved_id)
alembic.util.exc.CommandError: Can't locate revision identified by 'e39d16e62810'

My file structure looks like this:

app
-- views
----- __init__.py
----- main.py
-- __init__.py
-- config.py
-- models.py
instance
-- __init__.py
-- config.py
create_db.py
dev.db
run.py

My app factory:

from flask import Flask
from instance.config import app_config
from flask_migrate import Migrate

def create_app(config_name):
    """ Creates a runnable app.
        This app will be using the config with name "config_name".
    """
    app = Flask(__name__)
    # Loading the the config from instance folder with name "config_name"
    app.config.from_object(app_config[config_name])
    # Loading generic config from 'config.py'
    app.config.from_pyfile('config.py')

    # Registering this app at db
    from app.models import db
    db.init_app(app)
    migrate = Migrate(app, db)

    from app import models, views

    return app

My run.py:

""" This script runs a the app with the given configuration. """

from app import create_app

# Configuration used to run the app
config_name = 'dev'

# Creating the app by using the required configuration
app = create_app(config_name)

if __name__ == '__main__':
    app.run()

And my create_db.py file to create the database using models.py:

""" This script creates the database defined in app.models. """

from app import create_app

app = create_app('dev')
from app.models import db

# Telling SQLAlchemy what app should be used as the database model
with app.app_context():
    db.create_all()

This is my models.py:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Entry(db.Model):
    __tablename__ = 'Entries'
    layer_id = db.Column(db.Integer, primary_key=True)

    def __repr__(self):
        return "ID: {}; text: {}".format(self.layer_id, self.text)

EDIT: manage.py:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app
from app import models
from app.models import db

app = create_app('dev')
migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
10
can you check if you have a migration folder in your application directory?Espoir Murhabazi
There is/was no migration folder at the beginning. However it gets created when running "flask db init"Tobias Marschall
Delete the migrations directory and repeat the whole process again please. If you get the error, please add the command that gave you the error, along with the complete output to your question.Miguel
I already tried removing migrations directory but i didn´t solve the issue.Tobias Marschall
I encountered the same issue when I modified my models.py and tried migrating a second time. The issue is when you hit flask db init for the first time, it will create a table named alembic_version, you should drop that table from the database and the issue will be resolved.Furkhan Shaikh

10 Answers

35
votes

you delete the migration directory but the version has been saved in the database, so you have to delete the version info in the dabase, run

delete from alembic_version;

in mysql shell.

As suggested by @mirekphd, If this is a developing environment or a single app for test, just delete it, Else BACKUP the data in the table.

5
votes

In my case I have accidentally deleted the most recent migration file but the alembic version (alembic_version) table refers to the deleted version.

So instead of droping the entire database, you can change the version_num field in the alembic_version table.

Following steps worked for me:

  • Find the head using db history
  • Update the version_num field to the head version.
  • run migrate using db migrate
  • upgrade the database db upgrade
3
votes

I try this on flask and it solve!

python app.py db revision --rev-id e39d16e62810
python app.py db migrate
python app.py db upgrade

2
votes

Most of the time this happens, if you are at the development stage where you don't have much data to loose, you can drop the database and create a fresh one, alternatively, you can delete the migrations and begin the whole cycle again, for sqlite, it is all about deleting the sqlite file in your application, and beginning this cycle again. I hope to find the best solution to this verry soon.

1
votes

I found the solution. My mistake....path to database was wrong. Thank you anyways.

1
votes

Delete the history entry from the database will solve the issue.

Error: alembic.util.exc.CommandError: Can't locate revision identified by 'e39d16e62810'

select * from alembic_version where verion_num='e39d16e62810'

Then Delete this record:

delete from alembic_version where verion_num='e39d16e62810'
0
votes

In my case, since I was in the initial phase, I had the luxury of deleting the database file directly i.e. in my project folder there was a .sqlite file, so I deleted it by right-clicking it. But please keep in mind that I was in the initial phase, so I won't suggest this if you are not in the starting phase.

0
votes

For my case reason for the error was the relative path to sqlite db.

Fixed it by specifying the absolute path

app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{os.path.join(os.path.dirname(__file__), os.path.pardir, 'db.sqlite')}"

0
votes

I had the same error message but in my case it's because I used wrong database name in the connection string. Check your connection string

Error Message:

ERROR [root] Error: Can't locate revision identified by 'a80ab7ca5e1a'

Reason: My connection string was:

mysql+pymysql://kaunda:kaunda@localhost:3306/smis

Instead of

mysql+pymysql://kaunda:kaunda@localhost:3306/WorkFolder

The revision identified by "a80ab7ca5e1a" belongs to the database "smis" not "WorkFolder"

0
votes

Yet another cause of problems - making two flask projects in the same virtual environment.

I tried to make fake twin project for performance testing.

  • copied crucial parts of the original project
  • created new database
  • made changes in configuration file to point to new database
  • flask db init,
  • flask db migrate
  • got this error at first migration.

Then I did only one thing - created new python environment for this twin project - and error disappeared.

PS. Maybe it is possible to create two flask projects in the same environment, but I was not able to find solution.