Using Alembic API from inside application code

前端 未结 8 895
夕颜
夕颜 2020-12-08 04:06

I am using SQLite as an application file format (see here for why you would want to do this) for my PySide-based desktop application. That is, when a user uses my app, their

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 05:06

    For anyone else trying to achieve a flyway-esque result with SQLAlchemy, this worked for me:

    Add migration.py to your project:

    from flask_alembic import Alembic
    
    def migrate(app):
        alembic = Alembic()
        alembic.init_app(app)
        with app.app_context():
            alembic.upgrade()
    

    Call it on application startup after your db has been initialized

    application = Flask(__name__)
    db = SQLAlchemy()
    db.init_app(application)
    migration.migrate(application)
    

    Then you just need to do the rest of the standard alembic steps:

    Initialize your project as alembic

    alembic init alembic
    

    Update env.py:

    from models import MyModel
    target_metadata = [MyModel.Base.metadata]
    

    Update alembic.ini

    sqlalchemy.url = postgresql://postgres:postgres@localhost:5432/my_db
    

    Assuming your SQLAlchemy models are already defined, you can autogenerate your scripts now:

    alembic revision --autogenerate -m "descriptive migration message"
    

    If you get an error about not being able to import your model in env.py, you can run the following in your terminal fo fix

    export PYTHONPATH=/path/to/your/project
    

    Lastly, my migration scripts were getting generated in the alembic/versions directory, and I had to copy them to the migrations directory for alembic to pick them up.

    ├── alembic
    │   ├── env.py
    │   ├── README
    │   ├── script.py.mako
    │   └── versions
    │       ├── a5402f383da8_01_init.py  # generated here...
    │       └── __pycache__
    ├── alembic.ini
    ├── migrations
    │   ├── a5402f383da8_01_init.py  # manually copied here
    │   └── script.py.mako
    

    I probably have something misconfigured, but it is working now.

提交回复
热议问题