Flask-SQLAlchemy多个数据库和绑定

时间:2016-12-16 12:50:57

标签: python flask flask-sqlalchemy

URI:

SQLALCHEMY_DATABASE_URI = "mssql+pymssql://user:password123@127.0.0.1/DbOne"


SQLALCHEMY_BINDS = {
    "sql_server": "mysql+pymysql://user:password123@127.0.0.1/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"]

然而它抛出了一个KeyError,说'sbm_agents'表没有找到,因为我已经指定了绑定键指向sql_server绑定。

__初始化__。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 做了什么改变或者我错过了一步?

修改

对于想知道我是如何解决这个问题的人。 我直接去了SqlAlchemy并做了这个

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,但它的可行性有点单调乏味而且最初会引起混淆

1 个答案:

答案 0 :(得分:0)

使用db.reflect()代替db.Model.metadata.reflect(db.engine)