SQLAlchemy database migrations for Flask applications using Alembic

Overview

Flask-Migrate

Build status

Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. The database operations are provided as command-line arguments under the flask db command.

Installation

Install Flask-Migrate with pip:

pip install Flask-Migrate

Example

This is an example application that handles database migrations through Flask-Migrate:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))

With the above application you can create the database or enable migrations if the database already exists with the following command:

$ flask db init

Note that the FLASK_APP environment variable must be set according to the Flask documentation for this command to work. This will add a migrations folder to your application. The contents of this folder need to be added to version control along with your other source files.

You can then generate an initial migration:

$ flask db migrate

The migration script needs to be reviewed and edited, as Alembic currently does not detect every change you make to your models. In particular, Alembic is currently unable to detect indexes. Once finalized, the migration script also needs to be added to version control.

Then you can apply the migration to the database:

$ flask db upgrade

Then each time the database models change repeat the migrate and upgrade commands.

To sync the database in another system just refresh the migrations folder from source control and run the upgrade command.

To see all the commands that are available run this command:

$ flask db --help

Resources

Comments
  • sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqllite

    sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqllite

    I'm following precisely your Flask Mega-Tutorial (I bought the book ;-)). I'm using windows, and pipenv for my virtual environments.

    After executing p.40 << flask db init >> command I gave a look to the env.py file and pylint showed the error in the subject: Module 'alembic.context' has no 'config' member

    Nevertheless I run << flask db migrate -m "users table" >> and I had the following error: sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqllite

    Thank you in advance. Roberto

    question 
    opened by RobiIhs 34
  • Flask migrate couldn't read models?

    Flask migrate couldn't read models?

    I am trying to get the "python manage.py db migrate" to work but I keep getting these two lines only.

    INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL.

    Can someone explains what does the two lines mean? I am guessing the heroku backend that I am having couldn't compare the models.py and update the table. Correct me if I am wrong.

    In my view.py, I have "from models import *" and in my app.py, I have "from view.py".

    My friend has no problem migrating the database at all and he couldn't remember what he did to solve it.

    I ran "python manage.py db show" and it shows me this

    empty message

    Revision ID: b8b188e67d59 Revises: 5b82870de25a Create Date: 2018-08-31 13:24:27.359151

    I ran this "select * from alembic_version;" and I get

    version_num 32a4b24d4961

    Please let me know if the numbers makes any sense or the numbers are not helping at all. I just want to be able to update the table using the migrate and upgrade command whenever I add a column. and I have no idea what preventing it from reading my models.

    question 
    opened by Calvert-NYSSL 31
  • Flask-Migrate seems to not create tables on in-memory sqlite databases

    Flask-Migrate seems to not create tables on in-memory sqlite databases

    With SQLALCHEMY_DATABASE_URI = 'sqlite://', upgrade() doesn't appear to create tables.

    My tests fail with: OperationalError: (sqlite3.OperationalError) no such table

    question 
    opened by ColdHeat 27
  • "option values must be strings" error on db migrate

    I run

    $ python run.py db init

    And that runs without issue. Then,

    $ python run.py db migrate -m 'First migration'
    Traceback (most recent call last):
      File "run.py", line 3, in <module>
        myapp.manager.run()
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
        result = self.handle(sys.argv[0], sys.argv[1:])
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
        res = handle(*args, **config)
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/flask_script/commands.py", line 216, in __call__
        return self.run(*args, **kwargs)
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/flask_migrate/__init__.py", line 136, in migrate
        version_path=version_path, rev_id=rev_id)
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/alembic/command.py", line 113, in revision
        script.run_env()
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/alembic/script.py", line 390, in run_env
        util.load_python_file(self.dir, 'env.py')
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/alembic/util.py", line 243, in load_python_file
        module = load_module_py(module_id, path)
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/alembic/compat.py", line 79, in load_module_py
        mod = imp.load_source(module_id, path, fp)
      File "migrations/env.py", line 19, in <module>
        config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI'))
      File "/Users/bfh/.virtualenvs/myapp/lib/python2.7/site-packages/alembic/config.py", line 198, in set_main_option
        self.file_config.set(self.config_ini_section, name, value)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 743, in set
        raise TypeError("option values must be strings")
    TypeError: <flask_script.commands.Command object at 0x107aba950>: option values must be strings
    

    Any advice for a fella?

    opened by bllfrnch 26
  • flask db init fails: KeyError 'migrate'

    flask db init fails: KeyError 'migrate'

    Hi Miguel!

    I'm attempting to use your flask-migrate CLI tool as per your tutorial.

    Issue: Running flask db init from the terminal fails with error:

        directory = current_app.extensions['migrate'].directory
    KeyError: 'migrate' 
    

    Desired result: flask db init should create the database (sqlite) and initialize database tables from all models.

    Context:

    1. I've exported FLASK_APP='run.py', where run.py does the import of 'app' and 'db' from (myapp)/__init__.py
    2. Flask app is created with: app = Flask(APP_NAME) in run.py
    3. DB object is created with: db = SQLAlchemy(app) in run.py

    Speculative analysis: It seems that current_app.extensions is not somehow being populated with a desired key migrate, which I assume refers to your Flask extension.

    Where/how is that supposed to happen?

    There may be steps here I've missed or required parameters I'm unaware of. Can you point me in the right direction?

    Thanks!

    question 
    opened by fieldse 25
  • Flask not generating any migration

    Flask not generating any migration

    Hello there, I'm in a huge pickle. Flask-Migrate is not generating any migrations. I keep getting the following:

    INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
    INFO  [alembic.runtime.migration] Will assume transactional DDL.
    INFO  [alembic.env] No changes in schema detected.
    
    

    My directory structure is as follows:

    .
    ├── app
    │   ├── config.py
    │   ├── credentials.json
    │   ├── database.py
    │   ├── errors.py
    │   ├── factory.py
    │   ├── fake.json
    │   ├── models
    │   │   ├── helium.py
    │   │   ├── __init__.py
    │   │   ├── logs.py
    ├── app.db
    ├── credentials.json
    ├── env-example
    ├── fake.json
    ├── migrations
    │   ├── alembic.ini
    │   ├── env.py
    │   ├── env.pyc
    │   ├── README
    │   ├── script.py.mako
    │   └── versions
    ├── pytest.ini
    ├── README.md
    ├── requirements.txt
    ├── run.py
    ├── sample-loan.json
    ├── tasks.py
    ├── test.sh
    ├── worker.sh
    ├── wsgi.py
    
    

    Here's my main __init__.py file:

    from .factory import Factory
    
    
    def create_app(environment='development'):
        factory = Factory(environment)
        factory.set_flask()
        factory.set_celery()
    
        factory.set_db()
        factory.set_migration()
        from . import models
    
    
        factory.register(lms_blueprint)
        factory.register(mifos_blueprint)
        factory.register(br_blueprint)
    
        return factory.flask
    

    My model's __init__.py file is as follows:

    __all__ = ['helium', 'logs']
    

    My database.py file is as follows:

    from flask_migrate import Migrate
    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()
    migrate = Migrate()
    

    They are later initialized in factory.py below:

    from __future__ import absolute_import
    
    import logging
    import logging.config
    import os
    import sys
    from logging.handlers import RotatingFileHandler
    
    from flask import Flask
    
    from .config import config
    from .database import db, migrate
    from .tasks import celery_app, redis
    
    
    class Factory:
    
        def __init__(self, environment='development'):
            self._environment = os.environ.get('APP_ENVIRONMENT', environment)
    
        @property
        def environment(self):
            return self._environment
    
        @environment.setter
        def environment(self, environment):
            self._environment = environment
            self.flask.config.from_object(config[self._environment])
    
        def set_flask(self, **kwargs):
            self.flask = Flask(__name__, **kwargs)
            self.flask.config.from_object(config[self._environment])
            # setup logging
            file_handler = RotatingFileHandler('br.log', maxBytes=10000, backupCount=1)
            file_handler.setLevel(logging.INFO)
            self.flask.logger.addHandler(file_handler)
            stdout = logging.StreamHandler(sys.stdout)
            stdout.setLevel(logging.DEBUG)
            self.flask.logger.addHandler(stdout)
            # werkzeug = logging.getLogger('werkzeug')
            # werkzeug.setLevel(logging.DEBUG)
            # self.flask.logger.addHandler(werkzeug)
            return self.flask
    
        def set_celery(self, **kwargs):
            return celery_app
    
        def set_db(self):
            db.init_app(self.flask)
            return db
    
        def set_migration(self):
            migrate.init_app(self.flask, db)
            return migrate
    

    I can't get it to work with sqlite or postgres. I'm not sure if my directory structure is the problem or I'm missing a step. Some guidance would be highly appreciated.

    Thanks.

    question 
    opened by michaelbukachi 24
  • Migrate to multiple databases simultaneously

    Migrate to multiple databases simultaneously

    Greetings. I am doing a project and I need to migrate to several databases simultaneously. For example, I have bind 2 databases in SQLALCHEMY_BINDS like that :

     **app.config['SQLALCHEMY_BINDS'] = {
    'bobkov1': 'postgresql://postgres:zabil2012@localhost:5431/bobkov1',
    'bobkov' : 'postgresql://postgres:zabil2012@localhost:5431/bobkov'
    

    }**

    And now i want to migrate models to both of this databases. I'm tried to do it like that:

    **class User(BaseModel, db.Model): tablename = 'user' bind_key = {'bobkov','bobkov1'}

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    

    class Post(db.Model): tablename = 'post' bind_key = {'bobkov','bobkov1'} id = db.Column(db.Integer, primary_key=True) body = db.Column(db.String(140)) user_id = db.Column(db.Integer, db.ForeignKey('user.id'))**

    When trying to run this code, the model migrates only to the main database, which is defined in SQLALCHEMY_DATABASE_URI.

    Help me please, how to configure that?

    question 
    opened by BobkovS 22
  • KeyError: 'migrate' on heroku

    KeyError: 'migrate' on heroku

    when I try to run heroku flask db migrate or heroku flask db upgrade on Heroku. Heroku gives me the error below:

    Traceback (most recent call last): File "/app/.heroku/python/bin/flask", line 8, in sys.exit(main()) File "/app/.heroku/python/lib/python3.6/site-packages/flask/cli.py", line 967, in main cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None) File "/app/.heroku/python/lib/python3.6/site-packages/flask/cli.py", line 586, in main return super(FlaskGroup, self).main(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/app/.heroku/python/lib/python3.6/site-packages/click/core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/app/.heroku/python/lib/python3.6/site-packages/click/core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/app/.heroku/python/lib/python3.6/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/app/.heroku/python/lib/python3.6/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/click/decorators.py", line 21, in new_func return f(get_current_context(), *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/flask/cli.py", line 426, in decorator return __ctx.invoke(f, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/flask_migrate/cli.py", line 134, in upgrade _upgrade(directory, revision, sql, tag, x_arg) File "/app/.heroku/python/lib/python3.6/site-packages/flask_migrate/init.py", line 96, in wrapped f(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/flask_migrate/init.py", line 269, in upgrade config = current_app.extensions['migrate'].migrate.get_config(directory, KeyError: 'migrate'

    question 
    opened by techemmy 20
  • Flask-Migrate not creating tables

    Flask-Migrate not creating tables

    python manage.py db init && python manage.py db migrate && python manage.py db upgrade
    

    All commands run without error messages yet no tables were created. Here are the relevant files:

    project/__init__.py

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()
    
    def create_app():
        app = Flask(__name__)
        app.config.from_object(os.environ['APP_SETTINGS'])
        db.init_app(app)
        return app
    

    run.py

    from project import create_app
    app = create_app()
    
    if __name__ == "__main__":
        app.run()
    

    manage.py

    from flask_script import Manager
    from flask_migrate import Migrate, MigrateCommand
    from project.models import *
    from flask_sqlalchemy import SQLAlchemy
    from run import app
    
    
    db = SQLAlchemy(app)
    
    migrate = Migrate(app, db)
    manager = Manager(app)
    
    manager.add_command('db', MigrateCommand)
    
    if __name__ == '__main__':
        manager.run()
    
    question 
    opened by joekendal 19
  • ODBC Driver 17 for SQL Server doesn't work with multidb

    ODBC Driver 17 for SQL Server doesn't work with multidb

    I'm trying to change my project from a single database to multiple databases. I'm still building it, so it doesn't matter if I lose all of my data. But every time I do a flask db init --multidb and then try to run a flask db migrate, I get the below error:

    sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')

    If I run the init again without the multidb tag, everything works.

    Looking at the below item, it seems like it might be an SSL issue, but I'm not sure how to use any of the solutions, since I'm on a Windows computer. https://github.com/mkleehammer/pyodbc/issues/610

    question 
    opened by RRGTHWAR 18
  • Don't create DB and migrations from Flask

    Don't create DB and migrations from Flask

    My app.py

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_script import Manager
    from flask_migrate import Migrate, MigrateCommand
    from config import Config
    
    app = Flask(__name__)
    app.debug = True
    app.config.from_object(Config)
    
    db = SQLAlchemy(app)
    from models import Users
    
    migrate = Migrate(app, db)
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)
    
    
    
    if __name__ == '__main__':
        manager.run()
    

    models.py

    from app import db, app from datetime import date, datetime

    class Users(db.Model):
        # Users
        __tablename__ = 'users'
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        username = db.Column(db.String(120), index=True, unique=True)
        last_name = db.Column(db.String(128))
        first_name = db.Column(db.String(128))
        created = db.Column(db.DateTime, default=datetime.now())
        user_days = db.relationship("Days", back_populates="user_days")
        user_tasks = db.relationship("Tasks", back_populates="user_tasks")
        user_chats = db.relationship("Chats", back_populates="user_chats")
    
        def __init__(self, username, last_name, first_name):
            self.username = username
            self.last_name = last_name
            self.first_name = first_name
    
        def __repr__(self):
            return '<User {}>'.format(self.username)
    

    Run commands:

    python app.py db init
    python app.py db migrate
    python app.py db upgrade
    

    And have a problem:

    Traceback (most recent call last):
      File "app.py", line 12, in <module>
        from models import Users
      File "C:\Users\vandr\PycharmProjects\telegrambot_with_flask\models.py", line 1, in <module>
        from app import db, app
      File "C:\Users\vandr\PycharmProjects\telegrambot_with_flask\app.py", line 12, in <module>
        from models import Users
    ImportError: cannot import name 'Users'
    

    Can you help me?

    question 
    opened by vvandriichuk 17
  • Failure to run flask db migrate after upgrade 3.1 -> 4.0

    Failure to run flask db migrate after upgrade 3.1 -> 4.0

    With flask-alchemy 3.1.0 all works as expected. We add a column to one of the tables of the db.Model and all works as expected. It detected added columns and a new versions file is generated.

    After upgrade from flask-alchemy 3.1.0 to flask-alchemy 4.0.0 fails to detect any changes and generate a new versions file. There are no errors reported. It seems to fail to dive into the alembic.runtime.migration

    See attached logs

    flask-migrate_310.log poetry upgrade.log flask-migrate_400.log

    question 
    opened by ghaarsma 3
  • Migrations sometimes end with status 1

    Migrations sometimes end with status 1

    Hi there,

    I started to run into a weird issue in my GitHub actions. Sometimes my migrations just don't want to apply on my Postgres DB:

    The output of the step running on GitHub actions:

    INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
    INFO  [alembic.runtime.migration] Will assume transactional DDL.
    INFO  [alembic.runtime.migration] Running upgrade 616e0cbe0c24 -> 7001b6cb06f8, empty message.
    1
    

    The step does nothing difficult:

    docker-compose run --rm app sh -c "wait-for-it.sh db:5432 -- flask db upgrade -d /app/migrations heads"
    

    The migration itself is also easy:

    def upgrade():
        with op.get_context().autocommit_block():
            op.execute(
                """
                ALTER TYPE aggregationperiodtype ADD VALUE IF NOT EXISTS 'WEEKLY';
                """
            )
    

    This happens randomly (not always on this migration, sometimes on different and sometimes it passed without an error). Is it also possible to get more detail on this kind of error?

    requirements: Werkzeug==2.2.2 Flask==2.0.3 Flask-Migrate==3.1.0 Flask-SQLAlchemy==2.5.1 SQLAlchemy==1.4.31

    question 
    opened by itsdkey 3
  • Flask-Migrate fails with flask version 2.1.3

    Flask-Migrate fails with flask version 2.1.3

    We are using Flask-Migrate(version 3.1.0) from a long time and it used to work fine with our previous flask version BUT after upgrading our Flask version to 2.1.3 it's producing the below error on any flask db command

    Traceback (most recent call last):
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/bin/flask", line 8, in <module>
        sys.exit(main())
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/flask/cli.py", line 986, in main
        cli.main()
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/flask/cli.py", line 567, in main
        return super().main(*args, **kwargs)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/click/core.py", line 1055, in main
        rv = self.invoke(ctx)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
        return _process_result(sub_ctx.command.invoke(sub_ctx))
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
        return _process_result(sub_ctx.command.invoke(sub_ctx))
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
        return ctx.invoke(self.callback, **ctx.params)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/click/core.py", line 760, in invoke
        return __callback(*args, **kwargs)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/click/decorators.py", line 26, in new_func
        return f(get_current_context(), *args, **kwargs)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/flask/cli.py", line 407, in decorator
        return __ctx.invoke(f, *args, **kwargs)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/click/core.py", line 760, in invoke
        return __callback(*args, **kwargs)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/flask_migrate/cli.py", line 104, in migrate
        _migrate(directory, message, sql, head, splice, branch_label, version_path,
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/flask_migrate/__init__.py", line 98, in wrapped
        f(*args, **kwargs)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/flask_migrate/__init__.py", line 155, in migrate
        command.revision(config, message, autogenerate=True, sql=sql,
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/command.py", line 229, in revision
        script_directory.run_env()
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/script/base.py", line 569, in run_env
        util.load_python_file(self.dir, "env.py")
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/util/pyfiles.py", line 94, in load_python_file
        module = load_module_py(module_id, path)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/util/pyfiles.py", line 110, in load_module_py
        spec.loader.exec_module(module)  # type: ignore
      File "<frozen importlib._bootstrap_external>", line 850, in exec_module
      File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
      File "migrations/env.py", line 98, in <module>
        run_migrations_online()
      File "migrations/env.py", line 92, in run_migrations_online
        context.run_migrations()
      File "<string>", line 8, in run_migrations
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/runtime/environment.py", line 853, in run_migrations
        self.get_context().run_migrations(**kw)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/runtime/migration.py", line 611, in run_migrations
        for step in self._migrations_fn(heads, self):
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/command.py", line 205, in retrieve_migrations
        revision_context.run_autogenerate(rev, context)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/autogenerate/api.py", line 526, in run_autogenerate
        self._run_environment(rev, migration_context, True)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/autogenerate/api.py", line 544, in _run_environment
        if set(self.script_directory.get_revisions(rev)) != set(
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/script/base.py", line 296, in get_revisions
        self.revision_map.get_revisions(id_),
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/script/revision.py", line 527, in get_revisions
        return sum([self.get_revisions(id_elem) for id_elem in id_], ())
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/script/revision.py", line 527, in <listcomp>
        return sum([self.get_revisions(id_elem) for id_elem in id_], ())
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/script/revision.py", line 552, in get_revisions
        return tuple(
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/script/revision.py", line 553, in <genexpr>
        self._revision_for_ident(rev_id, branch_label)
      File "/Users/vinitpayal/engineering/tribes/codes/backend-api-python-3/venv/lib/python3.9/site-packages/alembic/script/revision.py", line 613, in _revision_for_ident
        assert resolved_id
    AssertionError
    

    The error appears on all

    flask db migrate -m
    flask db upgrade
    

    The error is being raised from a function named _revision_for_ident in dependency alembic BUT not sure what can be the cause of it and have no idea about how we can get it fixed.

    question 
    opened by ghost 5
  • Specify different username:password for Alembic than for SQLAlchemy

    Specify different username:password for Alembic than for SQLAlchemy

    I want to be able to specify a username:password to Flask-Migrate with permissions to alter tables and drop and create tables, but I don't want my SQLAlchemy user to have those permissions. SQLAlchemy should only be able to insert, update, select and join. Is this possible at the moment? If so, how would I do that?

    question 
    opened by L0uisc 1
  • Error: No such template 'custom_template'

    Error: No such template 'custom_template'

    Hi

    just trying to build the package for openSUSE and I'm getting

    Error: No such template 'custom_template'

    when running the tests. The tar-ball seems to have the custom_template directory missing that's in the test directory, is that the issue?

    question 
    opened by arunpersaud 4
  • `db migrate` success, but `db upgrade` fail, what can i do next?

    `db migrate` success, but `db upgrade` fail, what can i do next?

    run

    flask db migrate
    # return success
    
    # then
    flask db upgrade
    # return failed
    # o my models file define error,  so i corrected it.
    # then run
    flask db migrate
    # return:   ERROR [flask_migrate] Error: Target database is not up to date.
    

    What do I do in this case next?

    i fix models file, but can’t migrate or upgrade again.

    one way is delete all file, and db init again, but this is not what I want.

    question 
    opened by meimeitou 3
Owner
Miguel Grinberg
Miguel Grinberg
Adds SQLAlchemy support to Flask

Flask-SQLAlchemy Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy

The Pallets Projects 3.9k Dec 29, 2022
SqlAlchemy Flask-Restful Swagger Json:API OpenAPI

SAFRS: Python OpenAPI & JSON:API Framework Overview Installation JSON:API Interface Resource Objects Relationships Methods Custom Methods Class Method

Thomas Pollet 365 Jan 6, 2023
A Flask app template with integrated SQLAlchemy, authentication, and Bootstrap frontend

Flask-Bootstrap Flask-Bootstrap is an Flask app template for users to clone and customize as desired, as opposed to a Flask extension that you can ins

Eric S. Bullington 204 Dec 26, 2022
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 870 Jan 8, 2023
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 742 Feb 9, 2021
REST API with Flask and SQLAlchemy. I would rather not use it anymore.

Flask REST API Python 3.9.7 The Flask experience, without data persistence :D First, to install all dependencies: python -m pip install -r requirement

Luis Quiñones Requelme 1 Dec 15, 2021
Forum written for learning purposes in flask and sqlalchemy

Flask-forum forum written for learning purposes using SQLalchemy and flask How to install install requirements pip install sqlalchemy flask clone repo

Kamil 0 May 23, 2022
flask-apispec MIT flask-apispec (🥉24 · ⭐ 520) - Build and document REST APIs with Flask and apispec. MIT

flask-apispec flask-apispec is a lightweight tool for building REST APIs in Flask. flask-apispec uses webargs for request parsing, marshmallow for res

Joshua Carp 617 Dec 30, 2022
A basic CRUD application built in flask using postgres as database

flask-postgres-CRUD A basic CRUD application built in flask using postgres as database Taks list Dockerfile Initial docker-compose - It is working Dat

Pablo Emídio S.S 9 Sep 25, 2022
This is a simple web application using Python Flask and MySQL database.

Simple Web Application This is a simple web application using Python Flask and MySQL database. This is used in the demonstration of development of Ans

Alaaddin Tarhan 1 Nov 16, 2021
Lightweight library for providing filtering mechanism for your APIs using SQLAlchemy

sqlalchemy-filters-plus is a light-weight extendable library for filtering queries with sqlalchemy. Install pip install sqlalchemy-fitlers-plus Usage

Karami El Mehdi 38 Oct 5, 2022
A simple demo of using aiogram + async sqlalchemy 1.4+

aiogram-and-sqlalchemy-demo A simple demo of using aiogram + async sqlalchemy 1.4+ Used tech: aiogram SQLAlchemy 1.4+ PostgreSQL as database asyncpg a

Aleksandr 68 Dec 31, 2022
flask-reactize is a boostrap to serve any React JS application via a Python back-end, using Flask as web framework.

flask-reactize Purpose Developing a ReactJS application requires to use nodejs as back end server. What if you want to consume external APIs: how are

Julien Chomarat 4 Jan 11, 2022
Quick and simple security for Flask applications

Note This project is non maintained anymore. Consider the Flask-Security-Too project as an alternative. Flask-Security It quickly adds security featur

Matt Wright 1.6k Dec 19, 2022
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 2, 2023
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.1k Feb 17, 2021
A Flask web application that manages student entries in a SQL database

Student Database App This is a Flask web application that manages student entries in a SQL database. Users can upload a CSV into the SQL database, mak

rebecca 1 Oct 20, 2021
Flask Multiple Database Login

Flask Multiple Database Login Handle login with flask using two diferent databases: UE | European; BR | Brazilian; These databases are separed to resp

Jose Pedro 1 Dec 16, 2021
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 310 Dec 14, 2022