Flask 에서 DB 2개 이상 연결

최더디·2020년 10월 20일
0

방법


SQLAlchemy에 있는 SQLALCHEMY_BINDS 를 사용하면 된다.

SQLALCHEMY_BINDS 는 key-value 쌍으로 되어 있어 테이블에서 사용할 때 key 를 통해 불러올 수 있다.

#config.py
SQLALCHEMY_BINDS = {
        'test2': 'mysql+pymysql://localhost:8000/main'
    }

models.py안에서 __bind_key__ 를 통해서 위에서 정의한 key 값을 넣어주면 된다.

#models.py
class User(db.Model):
    """Users"""
    __tablename__ = 'users'
    **__bind_key__  = 'test2'**
    
    id          = db.Column(db.BigInteger, nullable=False, primary_key=True)
    user_email  = db.Column(db.String(100), nullable=False)

참고 사이트


http://blog.weirdx.io/post/50293

https://flask-sqlalchemy.palletsprojects.com/en/2.x/binds/

profile
focus on why

0개의 댓글