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:
run "python create_db.py"
run "flask db init"
add column "name" to Entry-model
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()
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.
I tried this on flask and it worked:
python app.py db revision --rev-id e39d16e62810
python app.py db migrate
python app.py db upgrade
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
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.
In my case, I have accidentally deleted the most recent migration file but the alembic version (alembic_version) table refers to the deleted version.
I tried the following:
flask db revision --rev-id [revision-id]
flask db migrate
flask db upgrade
My problem was that another flask app was already connected to the same database, so I just created a new database, and changed:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root#127.0.0.1:3306/newDataBaseName'
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 version_num='e39d16e62810'
Option 1: Update the record with your latest revision id
update alembic_version set version_num='<your_version_num>' where version_num='e39d16e62810'
Option 2: Delete this record:
delete from alembic_version where version_num='e39d16e62810'
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')}"
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.
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.
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"
Make sure you set FLASK_APP=app.py on windows or export FLASK_APP=app.py on MAC before running flask db init, then flask db migrate -m "message" and flask db upgrade. You can check this link for more info https://pypi.org/project/Flask-Migrate/
I'm trying to test my datastore with unittest on my GAE application running locally
when i'm running a simple query on the datastore, I get an error from my virtualenv:
Error
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 331, in run
testMethod()
File "/Users/thibault/projects/backend/cron/gmail/test_gmail_api.py", line 40, in test_get_conversation_id_by_email
res = get_conversation_id_from_email('test#gmail.com')
File "/Users/thibault/projects/backend/cron/gmail/api_gmail.py", line 158, in get_conversation_id_from_email
user_list = User.query(User.emails == email_user).fetch(use_cache=True, use_memcache=True)
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/utils.py", line 160, in positional_wrapper
return wrapped(*args, **kwds)
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/query.py", line 1218, in fetch
return self.fetch_async(limit, **q_options).get_result()
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/utils.py", line 160, in positional_wrapper
return wrapped(*args, **kwds)
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/query.py", line 1238, in fetch_async
qry = self._fix_namespace()
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/query.py", line 922, in _fix_namespace
namespace = namespace_manager.get_namespace()
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/api/namespace_manager/namespace_manager.py", line 88, in get_namespace
name = _config.default_namespace_for_request()
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/api/lib_config.py", line 351, in __getattr__
self._update_configs()
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/api/lib_config.py", line 287, in _update_configs
self._registry.initialize()
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/api/lib_config.py", line 160, in initialize
import_func(self._modname)
File "/Users/thibault/projects/backend/appengine_config.py", line 8, in <module>
vendor.add('lib')
File "/Users/thibault/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/vendor/__init__.py", line 44, in add
'No such virtualenv or site directory' % path)
ValueError: virtualenv: cannot access lib: No such virtualenv or site directory
I'm using the ide pycharm. I don't understand why it can't find the lib folder because, when I run my app locally, there is no problem at all.
the error append only when I run a test.
here is my test:
class TestBodyMail(unittest.TestCase):
def test_get_conversation_id_by_email(self):
res = get_conversation_id_from_email('test#gmail.com')
self.assertEqual(res,'2a4427fe77d2f0d2')
res = get_conversation_id_from_email('test#not_a_user.com')
self.assertEqual(res, None)
if __name__ == '__main__':
unittest.main()
the tested function:
def get_conversation_id_from_email(email_user):
"""
Args:
email_user: the email user
Returns:
the conversation id
"""
user_list = User.query(User.emails == email_user).fetch(use_cache=True, use_memcache=True)
if len(user_list) == 0:
return None
for user_match in user_list:
return user_match.device_ids[0]
Create appengine_config.py in the root of project, and put this:
import os
from google.appengine.ext import vendor
vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))
Also, add lib package into root of project if it is not there.
In my case it solved the issue.
I'm using gaesessions. When I try to check the current sessions by doing get_current_session() I get the following error:
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 716, in __call__
handler.post(*groups)
File "C:\Users\roger\Documents\projects\myapp\handlers\unburden.py", line 502, in post
session = get_current_session()
File "C:\Users\roger\Documents\projects\myapp\gaesessions\__init__.py", line 37, in get_current_session
return _tls.current_session
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\dist\_threading_local.py", line 215, in __getattribute__
return object.__getattribute__(self, name)
AttributeError: 'local' object has no attribute 'current_session'
I have already created the appengine_config.py file, and here it is:
from gaesessions import SessionMiddleware
COOKIE_KEY = '\x91G{\xd8\x90\x1e\xa4\xfdcd\x0fd\x0cXt\xd4 d\x97\x06YV\xaa_\x99\x95\x9d\xbc&\x83\x98\xb4h\xa5\xc1\xdau\xd5\x03\xc6u\xc7\x15<!V\x9d\xd9\xef\xa4Z\xce\x7f\x06*i\xca\xd2\x9f\xcdE|\x1fV'
def webapp_add_wsgi_middleware(app):
app = SessionMiddleware(app, cookie_key=COOKIE_KEY)
return app
I created the COOKIE_KEY by running os.urandom(64) on an python interpreter. I don't know what might be causing this, since I've seen a question about this problem, and it says you must create the appengine_config.py file and configure the middleware, but it's already done.
OBS: I'm NOT using Python27 on my GAE application.
Any ideas? Thank you.
I'm having some trouble implementing the Cork library with a Bottle app. I've tried setting up the example app, and I made some minor modifications to get it to run in an WSGI container. The main change is that I changed this:
if __name__ == "__main__":
main()
to this:
application = default_app()
When I authenticate with the admin user, I get the following:
Traceback (most recent call last):
File "/path_to_app/lib/python2.7/bottle-0.11.4-py2.7.egg/bottle.py", line 763, in _handle
return route.call(**args)
File "/path_to_app/lib/python2.7/bottle-0.11.4-py2.7.egg/bottle.py", line 1572, in wrapper
rv = callback(*a, **ka)
File "/path_to_app/cork-example/simple_webapp.py", line 47, in login
aaa.login(username, password, success_redirect='/', fail_redirect='/login')
File "build/bdist.linux-x86_64/egg/cork/cork.py", line 209, in login
self._setup_cookie(username)
File "build/bdist.linux-x86_64/egg/cork/cork.py", line 610, in _setup_cookie
session['username'] = username
TypeError: 'NoneType' object does not support item assignment
When I attempt to view the main page, I get this error:
Traceback (most recent call last):
File "/path_to_app/lib/python2.7/bottle-0.11.4-py2.7.egg/bottle.py", line 763, in _handle
return route.call(**args)
File "/path_to_app/lib/python2.7/bottle-0.11.4-py2.7.egg/bottle.py", line 1572, in wrapper
rv = callback(*a, **ka)
File "/path_to_app/cork-example/simple_webapp.py", line 90, in index
aaa.require(fail_redirect='/login')
File "build/bdist.linux-x86_64/egg/cork/cork.py", line 267, in require
cu = self.current_user
File "build/bdist.linux-x86_64/egg/cork/cork.py", line 417, in current_user
username = session.get('username', None)
AttributeError: 'NoneType' object has no attribute 'get'
Is there a newbie mistake I might be making? Or is something else wrong?
I figured it out. It was a newbie mistake. The Bottle documentation says that if you want to use Bottle with mod_wsgi, toward the end of the file, you should use this:
application = default_app()
After getting a better understanding of how this all works, I realized I was sending the wrong application object to mod_wsgi. Instead, I should have used this:
application = app #app was defined earlier in the example application
I have my Flask app which uses Flask-Assets and while trying to run the unittest cases, except the first testcase, others fails with the following RegisterError.
======================================================================
ERROR: test_login_page (tests.test_auth.AuthTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/cnu/env/flenv/lib/python2.7/site-packages/nose/case.py", line 133, in run
self.runTest(result)
File "/Users/cnu/env/flenv/lib/python2.7/site-packages/nose/case.py", line 151, in runTest
test(result)
File "/Users/cnu/env/flenv/lib/python2.7/site-packages/flask_testing.py", line 72, in __call__
self._pre_setup()
File "/Users/cnu/env/flenv/lib/python2.7/site-packages/flask_testing.py", line 80, in _pre_setup
self.app = self.create_app()
File "/Users/cnu/Projects/Bookworm/App/tests/test_auth.py", line 8, in create_app
return create_app('testing.cfg')
File "/Users/cnu/Projects/Bookworm/App/bookworm/__init__.py", line 118, in create_app
configure_extensions(app)
File "/Users/cnu/Projects/Bookworm/App/bookworm/__init__.py", line 106, in configure_extensions
assets.register('js_all', js)
File "/Users/cnu/env/flenv/src/webassets/src/webassets/env.py", line 374, in register
'as "%s": %s' % (name, self._named_bundles[name]))
RegisterError: Another bundle is already registered as "js_all": <Bundle output=assets/packed.js, filters=[<webassets.filter.jsmin.JSMin object at 0x10fa8af90>], contents=('js/app.js',)>
My understanding of why this happens in before the first testcase is run, create_app creates an instance of app and this is maintained for all other testcases.
I tried del(app) in the teardown method, but doesn't help.
Is there some way to fix it?
You probably have a global object for the assets environment, which you have declared as such :
in file app/extensions.py:
from flask.ext.assets import Environment
assets = Environment()
Then, somewhere in your create_app method, you should init the environment:
in file app/__init__.py:
from .extensions import assets
def create_app():
app = Flask(__name__)
...
assets.init_app(app)
...
return app
The thing is that when you initialize your environment with you app, the registered bundles aren't cleared. So you you should do it manually as such in your TestCase:
in file tests/__init__.py
from app import create_app
from app.extensions import assets
class TestCase(Base):
def create_app(self):
assets._named_bundles = {} # Clear the bundle list
return create_app(self)
Hope this helps,
Cheers