2016-12-16 2 views
1

URI :플라스크-SQLAlchemy의 여러 데이터베이스와 결합

SQLALCHEMY_DATABASE_URI = "mssql+pymssql://user:[email protected]/DbOne" 


SQLALCHEMY_BINDS = { 
    "sql_server": "mysql+pymysql://user:[email protected]/DbTwo" 
} 

Models.py

class CrimMappings(db.Model): 
    __tablename__ = "crim_mappings" 
    id = db.Column(db.Integer, primary_key=True) 
    date_mapped = db.Column(db.Date) 
    county_id = db.Column(db.Integer) 
    state = db.Column(db.String(20)) 
    county = db.Column(db.String(100)) 
    AgentID = db.Column(db.String(100), unique=True) 
    CollectionID = db.Column(db.String(100)) 
    ViewID = db.Column(db.String(100)) 


class LicenseType(db.Model): 
    __bind_key__ = "sql_server" 
    __table__ = db.Model.metadata.tables["sbm_agents"] 

는 'sbm_agents'테이블을 찾을 수없는 말을 나에게 KeyError을 던져 그러나 어떤을 바인드 키가 sql_server 바인드를 가리 키도록 지정했기 때문에 거기에 있어야합니다.

__init__.py

from os.path import join,dirname,abspath 

from flask_admin import Admin 
from project.apps.flask_apps.user_app.forms import UserAdminForm 
from flask_admin.contrib.sqla import ModelView 

from project import app_factory, db 
from project.apps.flask_apps.admin_own.views import AdminHome, Utilities 
from project.apps.flask_apps.admin_own.models import CredentCheckMappings, AllAgents, LicenseTypes 
from project.apps.flask_apps.admin_own.forms import MasterAgentForm, AgentMappingsModelView, AllLicenseForm 
from project.apps.flask_apps.user_app.models import Users 


def create_application(): 
    config_path = join(dirname(abspath(__file__)), "config", "project_config.py") 
    app = app_factory(config_path=config_path) 
    admin = Admin(app, template_mode="bootstrap3", base_template="base_templates/admin_base.html", 
       index_view=AdminHome()) 
    with app.app_context(): 
     db.create_all() 
     db.Model.metadata.reflect(db.engine) 
     admin.add_view(MasterAgentForm(AllAgents, db.session)) 
     admin.add_view(UserAdminForm(Users, db.session)) 
     admin.add_view(Utilities(name="Utilities", endpoint="utilities")) 
     admin.add_view(AgentMappingsModelView(CredentCheckMappings, db.session)) 
     admin.add_view(AllLicenseForm(LicenseTypes, db.session)) 
    return app 

application = create_application() 


if __name__ == "__main__": 
    application.run(host="0.0.0.0", port=5000, debug=True) 

내가 여기에 무엇을 놓치고? 나는이 시도했다 : flask sqlalchemy example around existing database

을하지만 메신저는 점점 KeyError 뭔가 변화 또는 메신저 단계 누락이나요?

편집 : 나는이 문제를 가지고 방법을 알고 싶은 사람들을 위해

. 내가 바로 SqlAlchem ​​y의에 가서 그런 식으로 메신저가 전체 데이터베이스를 반영하고 특정 테이블을 반영하도록 선택하지이

from sqlalchemy import create_engine, MetaData 
from sqlalchemy.orm import scoped_session, sessionmaker 
from sqlalchemy.ext.automap import automap_base 
from urllib.parse import quote_plus 

engine = create_engine("mssql+pyodbc:///?odbc_connect="+ quote_plus("DRIVER={FreeTDS};SERVER=172.1.1.1;PORT=1433;DATABASE=YourDB;UID=user;PWD=Password")) 
metadata = MetaData(engine) 
Session = scoped_session(sessionmaker(bind=engine)) 

LicenseType= Table("sbm_agents", metadata, autoload=True) 

했다. 왜냐하면 전체 데이터베이스를 반영하는 것이 느리기 때문입니다.

당신이 FREETDS을 구성해야하지만 때문에이 방법이 조금 험악하지만 처음

답변

0

사용 db.reflect() 대신 db.Model.metadata.reflect(db.engine)에서 조금 지루하고 혼란의 해 드리겠습니다.

+0

나는 아직도 나를 못 들었습니다 ... 왜 그런지는 모르겠지만'LicenseType' 모델에서'db.Model.metadata.tables.keys()'를 할 때마다 나는 여전히'keys'를 얻습니다 바인드 키를 지정 했음에도 불구하고 기본 'URI'를 사용했습니다.이 문제는 flask-sqlalchemy를 완전히 우회하여 직접 sqlalchemy로 이동합니다. –