问题
Problem: there needs to be full working example of auto-mapping sqlalchemy to an existing database in an app with multiple binds.
I want to bind to two databases and have one auto-map the tables. I need to do this because i don't have control over one DB, thus would have to constantly re-write my models and might delete new tables every time i migrate.
I love the answers given here, but i can't seem to make it work in Flask (I am able to use the sqlalchemy only to query as per the example).
The model.py I set up from the example above results in
EDIT I pulled the line
db.Model.metadata.reflect[db.engine]
from another post, and it should be db.Model.metadata.reflect(db.engine) very simple solution
here is my model.py
from app import db
from sqlalchemy.orm import relationship
db.Model.metadata.reflect[db.engine]#change to (db.engine)
class Buildings(db.Model):
__table__ = db.Model.metadata.tables['test']
__bind_key__ = 'chet'
def __repr__(self):
return self.test1
.... other models from sqlalchemy uri here...
i get this
>>> from app import db, models
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "app/__init__.py", line 69, in <module>
from app import views, models
File "app/views.py", line 1, in <module>
from app import app,models, db
File "app/models.py", line 163, in <module>
db.Model.metadata.reflect[db.engine]
TypeError: 'instancemethod' object has no attribute '__getitem__'
Here's my config.py
SQLALCHEMY_DATABASE_URI = 'postgresql://chet@localhost/ubuntuweb'
SQLALCHEMY_BINDS = {
'chet': 'postgresql://chet@localhost/warehouse',
}
here's my init.py file
from flask import Flask
from flask_bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin import Admin, BaseView, expose
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.login import LoginManager, UserMixin, login_required
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'app/static'
app.config.from_object('config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
Bootstrap(app)
from app import views, models
admin = Admin(app)
回答1:
Your code has
db.Model.metadata.reflect[db.engine]
When it should be
db.Model.metadata.reflect(db.engine) # parens not brackets
This should have been pretty obvious from the stack trace....
来源:https://stackoverflow.com/questions/33248702/flask-sqlalchemy-example-around-existing-database