I have used sql-alchemy for so long but I don't know it suddnly stopped working and showing me errors
Code
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# create the extension
db = SQLAlchemy()
# create the app
app = Flask(__name__)
# configure the SQLite database, relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
# initialize the app with the extension
db.init_app(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique=True, nullable=False)
email = db.Column(db.String)
with app.app_context():
db.create_all()
this is code available on sqlalchemy documentation
Error
(venv) viral#viral-Lenovo:~/Desktop/sql-practice$ python main.py
Traceback (most recent call last):
File "/home/viral/Desktop/sql-practice/main.py", line 11, in <module>
db.init_app(app)
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 326, in init_app
engines[key] = self._make_engine(key, options, app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 614, in _make_engine
return sa.engine_from_config(options, prefix="")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py", line 817, in engine_from_config
return create_engine(url, **options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 2, in create_engine
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/util/deprecations.py", line 277, in warned
return fn(*args, **kwargs) # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py", line 605, in create_engine
dbapi = dbapi_meth(**dbapi_args)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/viral/Desktop/sql-practice/venv/lib/python3.11/site-packages/sqlalchemy/dialects/sqlite/pysqlite.py", line 504, in import_dbapi
from sqlite3 import dbapi2 as sqlite
File "/usr/local/lib/python3.11/sqlite3/__init__.py", line 57, in <module>
from sqlite3.dbapi2 import *
File "/usr/local/lib/python3.11/sqlite3/dbapi2.py", line 27, in <module>
from _sqlite3 import *
ModuleNotFoundError: No module named '_sqlite3'
I expected that it will create a database by creating new folder called instance. but it's only creating instance folder but not database
I have tried creating new venv, reinstalling python and restarting pc but still it's showing the same error.
note: I am using Linux, Ubuntu Kde plasma
Related
When I run
heroku run python
>>> from app.main import app
>>> app.config['SQLALCHEMY_DATABASE_URI']
'postgres://<url string>' # the database url is passed correctly
>>> from app.main import db
>>> db.create_all()
it gives this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 962, in get_engine
return connector.get_engine()
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 556, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options)
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 972, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts)
File "<string>", line 2, in create_engine
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/util/deprecations.py", line 298, in warned
return fn(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/engine/create.py", line 520, in create_engine
entrypoint = u._get_entrypoint()
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/engine/url.py", line 653, in _get_entrypoint
cls = registry.load(name)
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 342, in load
"Can't load plugin: %s:%s" % (self.group, name)
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres
I'm confused because I'm new to Heroku and Postgresql (been using SQLite until now) and none of the tutorials I'm following explain how it all connects to Flask, only how to do it. So I don't understand what to look at to fix the problem. Is there any other code I should include in the question?
(Most of the other questions like this one are typos or errors that don't fix this issue.)
This is due to a change in the sqlalchemy library. It was an announced deprecation in the changing of the dialect (the part before the ':' in the SQLALCHEMY_DATABASE_URI) name postgres to postgresql. They released this breaking change from this github commit with a minor version release, which is in their policy to do so.
Heroku's default dialect is postgres in the DATABASE_URL they provide, which gets translated into the SQLALCHEMY_DATABASE_URI. Heroku could update their postgres add-on if updating does not break other libraries which might depend on it.
In the meantime, you can pin your sqlalchemy library back to <1.4.0 (1.3.23 is the last 1.3.x release), and it should work.
Alternatively, you can update your code to modify the dialect.
Here's a quick one that works for me, with the latest PostgreSQL on Heroku:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL').replace("://", "ql://", 1)
Just hacks the postgres:// from Heroku (which can't be edited) to postgresql://.
When I run
heroku run python
>>> from app.main import app
>>> app.config['SQLALCHEMY_DATABASE_URI']
'postgres://<url string>' # the database url is passed correctly
>>> from app.main import db
>>> db.create_all()
it gives this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 962, in get_engine
return connector.get_engine()
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 556, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options)
File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 972, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts)
File "<string>", line 2, in create_engine
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/util/deprecations.py", line 298, in warned
return fn(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/engine/create.py", line 520, in create_engine
entrypoint = u._get_entrypoint()
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/engine/url.py", line 653, in _get_entrypoint
cls = registry.load(name)
File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 342, in load
"Can't load plugin: %s:%s" % (self.group, name)
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres
I'm confused because I'm new to Heroku and Postgresql (been using SQLite until now) and none of the tutorials I'm following explain how it all connects to Flask, only how to do it. So I don't understand what to look at to fix the problem. Is there any other code I should include in the question?
(Most of the other questions like this one are typos or errors that don't fix this issue.)
This is due to a change in the sqlalchemy library. It was an announced deprecation in the changing of the dialect (the part before the ':' in the SQLALCHEMY_DATABASE_URI) name postgres to postgresql. They released this breaking change from this github commit with a minor version release, which is in their policy to do so.
Heroku's default dialect is postgres in the DATABASE_URL they provide, which gets translated into the SQLALCHEMY_DATABASE_URI. Heroku could update their postgres add-on if updating does not break other libraries which might depend on it.
In the meantime, you can pin your sqlalchemy library back to <1.4.0 (1.3.23 is the last 1.3.x release), and it should work.
Alternatively, you can update your code to modify the dialect.
Here's a quick one that works for me, with the latest PostgreSQL on Heroku:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL').replace("://", "ql://", 1)
Just hacks the postgres:// from Heroku (which can't be edited) to postgresql://.
I started learning how to use SQLAlchemy for my code but for some reason when I ran the code it raised this exception:
Traceback (most recent call last):
File "C:/Users/smadar.KLAG/PycharmProjects/keylogger/site/practice.py", line 118, in <module>
db.create_all()
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1039, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1031, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
return connector.get_engine()
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 555, in get_engine
options = self.get_options(sa_url, echo)
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 570, in get_options
self._sa.apply_driver_hacks(self._app, sa_url, options)
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 914, in apply_driver_hacks
sa_url.database = os.path.join(app.root_path, sa_url.database)
AttributeError: can't set attribute
This is the code:
from flask import Flask, redirect, url_for, render_template, request, session, flash
from time import sleep
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
class Users(db.Model):
_id = db.Column("id", db.Integer, primary_key=True)
email = db.Column(db.String(100))
password = db.Column(db.String(100))
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
I tried running the code of a friend of mine that has SQLAlchemy (the code does work for him) incase it was a coding issue but I have reached the same error with his code as well.
Is there something I am doing incorrectly?
I just ran into this too. Looks like SQLAlchemy just released version 1.4, which breaks flask_sqlalchemy.
I was able to resolve the issue on my system by installing the previous (1.3) version instead.
EDIT: the latest version of SQLAlchemy works now (version 1.4 as of writing this)
installing SQLAlchemy 1.3.23 worked for me.
pip install SQLAlchemy==1.3.23
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 building an API service with Flask, SQLAlchemy and more recently integrating the Flask-SQLAlchemy extension. While I can run the app standalone and make API calls successfully, I am hitting a problem attempting to run unittests. I believe the issue is with importing the db.Model types more than once.
The exception is this:
Error
Traceback (most recent call last):
File "/Users/james/.pyenv/versions/2.7.10/lib/python2.7/unittest/case.py", line 322, in run
self.setUp()
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/tests/test_users.py", line 28, in setUp
from trustmile.app.users.model import User, ConsumerUser, CourierUser, AuthSession, Location, UserAddress, db
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/users/model.py", line 23, in <module>
class User(db.Model, UniqueMixin, TableColumnsBase, References):
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 536, in __init__
DeclarativeMeta.__init__(self, name, bases, d)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/api.py", line 55, in __init__
_as_declarative(cls, classname, cls.__dict__)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 88, in _as_declarative
_MapperConfig.setup_mapping(cls, classname, dict_)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 103, in setup_mapping
cfg_cls(cls_, classname, dict_)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 131, in __init__
self._setup_table()
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 394, in _setup_table
**table_kw)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 398, in __new__
"existing Table object." % key)
InvalidRequestError: Table 'tmuser' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
My init.py in /app/ (the top level) is like this:
__author__ = 'james'
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import config
from app.messaging import EmailHandler
app = Flask(__name__, static_folder='api/static', static_url_path='/static')
app.config.from_object(config)
db = SQLAlchemy(app)
EmailHandler.setup(config.EMAIL_API_KEY_DEV)
from app.api.consumer_v1 import bp as blueprint
app.register_blueprint(blueprint, url_prefix = '/consumer/v1')
app.test_request_context()
Running that with:
from app import app
app.run(debug=True, host='0.0.0.0', port=5001)
Works great.
The beginning of my test_users.py looks like this:
__author__ = 'james'
from trustmile.app.exc import InvalidEmailException
from trustmile.app.exc import InsecurePasswordException
from nose.tools import assert_true, raises
from trustmile.app.users.model import User, ConsumerUser, CourierUser, AuthSession, Location, UserAddress, db
from . import TransactionalTest
email_address = 'james#cloudadvantage.com.au'
test_password = 'mypassword'
class UserTest(TransactionalTest):
#classmethod
def setUpClass(cls):
super(UserTest, cls).setUpClass()
def setUp(self):
super(UserTest, self).setUp()
def test_create_user(self):
user = User()
db.session.add(user)
It must be fairly common way to do unit testing and yes I'm sharing the SQLAlchemy object between modules (which I'm sure is bad practice). I'm running it with nosetests and the error occurs as the code is initialised. Sorry for the lengthy question, hopefully someone can help me!
__table_args__ = {'extend_existing': True}
right below __tablename__