A better approach is to include the --directory option in the flask db migrate command. This way you can link the projects passing the path of the migrations folder in the reference project
To make it easier to understand I made an example in 3 steps:
- In the first project, you can define the connection between the tables using a "bind" type relationship, which allows a table from a database to connect to another table from a different database. To do this, define the Coupon class again, this time using the bind_key() function to specify the connection to the second database.
#project 1
class Cupom(db.Model):
__tablename__ = 'cupom'
__bind_key__ = 'db2'
id = db.Column(db.Integer, primary_key=True)
name= db.Column(db.String(50), nullable=False)
#project 2
class Cupom(db.Model):
__tablename__ = 'cupom'
id = db.Column(db.Integer, primary_key=True)
name= db.Column(db.String(50), nullable=False)
- Configure the database connection in each project. Each project must have its own database and its own connection credentials. You can configure this information in a configuration file or in environment variables.
# Database setup for the first project
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@localhost/db1'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_BINDS'] = {
'db2': 'mysql://user:password@localhost/db2'
}
db.init_app(app)
# Database setup for the second project
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@localhost/db2'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
- Perform database migrations on each project using Flask-Migrate. For the first project, specify the connection to the second database using the --directory option in the flask db migrate command.
# Running the migrations on the first project
export FLASK_APP=projeto1
flask db init
flask db migrate --directory=../projeto2/migrations
flask db upgrade
# Running the migrations on the second project
export FLASK_APP=projeto2
flask db init
flask db migrate
flask db upgrade
Something that might be useful. To separate a migration for your project's models and another for shared models you need to create a directory, inside one of the 2 projects or inside a git submodule/subtree they use and make a new flask db init, flask_migrate and upgrade inside him