I’m struggling to create tables in the second database. I’ve tried many options, but the tables just won’t create. If I use the main database (without specifying binds), everything creates and works fine, but in the second database, using db.Table, no tables are created (tables created through classes work without any issues)
# config.py
class BaseConfig:
app_dir_name = os.path.dirname(__file__)
main_db_path = os.path.join(app_dir_name, 'main.db')
to_do_db_path = os.path.join(app_dir_name, 'to_do.db')
appmeta_db_path = os.path.join(app_dir_name, 'appmeta.db')
SQLALCHEMY_DATABASE_URI = f'sqlite:///{main_db_path}'
SQLALCHEMY_BINDS = {
'to_do_base': f'sqlite:///{to_do_db_path}',
'app_session_meta': f'sqlite:///{appmeta_db_path}'
}
# __init.py__
from .config import BaseConfig
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from app.socketio_instance import socketio
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_type='work'):
app = Flask(__name__)
socketio.init_app(app)
if config_type == 'test':
CORS(app, resources={r"/*": {"origins": "*"}})
app.config.from_object(TestingConfig)
TestingConfig.init_app(app)
print('test')
else:
raise ValueError("Invalid configuration type")
db.init_app(app)
with app.app_context():
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .tasks import to_do_app as tasks_blueprint
app.register_blueprint(tasks_blueprint, url_prefix='/tasks')
from .dashboard import dashboard as dashboard_blueprint
app.register_blueprint(dashboard_blueprint)
db.create_all()
migrate.init_app(app, db)
return app
from app import db
db.metadata.schema = 'to_do_base'
# ToDoBase
# it's work
class List(db.Model):
__tablename__ = 'lists'
__bind_key__ = 'to_do_base'
id = db.Column('ListID', db.Integer, primary_key=True)
name = db.Column('ListName', db.String(255))
# don't work:
task_list_relations = db.Table('task_list_relations', db.metadata, db.Column('TaskID', db.Integer, db.ForeignKey('tasks.TaskID'), primary_key=True), db.Column('ListID', db.Integer, db.ForeignKey('lists.ListID'), primary_key=True))`
I try:
1.
db.metadata.schema = 'to_do_base'
task_list_relations = db.Table('task_list_relations', db.metadata, ...)
list_group_relations = db.Table('list_group_relations', ... , bind_key='to_do_base')
3.
metadata = MetaData(schema='to_do_base')
list_group_relations = db.Table('list_group_relations', metadata, bind_key='to_do_base')
metadata = MetaData(schema='to_do_base')
list_group_relations = db.Table('list_group_relations', metadata, info={'bind_key': 'to_do_base'})
The main problem is that tables created using db.Table are not being created in the desired database. If everything is created in the main database, it works, but when I try to create it in the database using bind_key, nothing is created.
Mikhail is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.