美文网首页
flask-sqlalchemy 链接多数据库的配置及多数据库同

flask-sqlalchemy 链接多数据库的配置及多数据库同

作者: 小钟钟同学 | 来源:发表于2019-06-14 16:14 被阅读0次

    说明:因使用到flask再同一个应用里面需要链接多个数据库的链接处理,所以需要的进行像配置

    1:配置连接:

    #连接主要数据库
    SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://postgres:123456@localhost:5432/xmly_admin_sys'
    
    # 连接到其他的数据库
    SQLALCHEMY_BINDS = {
        'lincms3': 'postgresql+psycopg2://postgres:123456@localhost:5432/lincms3',
        'lincms4': 'postgresql+psycopg2://postgres:123456@localhost:5432/lincms4',
        'users': 'sqlite:///users.db',
        'appmeta': 'sqlite:///appmeta.db'
    }
    

    2:表格创建

    PS:创建对于的表格模型的话,需要在之前引入加载一次的对于的模型:

    # 表格创建
    def create_tables(app):
        from aframecore.db import db
        with app.app_context():
            db.create_all()
            db.create_all(bind='lincms3')
            db.create_all(bind='lincms4')
            #或者
             db.create_all(bind=['lincms3','lincms4'])
    
    

    3:解决多数据库存在同表表名的时候存在异常信息提示:

    sqlalchemy.exc.InvalidRequestError: Table 'book' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
    

    解决:添加: table_args = {"useexisting": True}

    class Book(Base):
        __bind_key__ = 'lincms4'
        __tablename__ = 'book'  # 未设置__bind_key__,则采用默认的数据库引擎
        __table_args__ = {"useexisting": True}
    
        id = Column(Integer, primary_key=True, autoincrement=True)
        title = Column(String(50), nullable=False)
        author = Column(String(30), default='未名')
        summary = Column(String(1000))
        image = Column(String(50))
        imagessss = Column(String(50))
    

    相关文章

      网友评论

          本文标题:flask-sqlalchemy 链接多数据库的配置及多数据库同

          本文链接:https://www.haomeiwen.com/subject/vgspfctx.html