title: flask sqlalchemy example around existing database
body: <p><strong>Problem:</strong> there needs to be full working example of auto-mapping sqlalchemy to an existing database in an app with multiple binds.</p>
  
  <p>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.</p>
  
  <p>I love the answers given <a href="https://stackoverflow.com/questions/17652937/how-to-build-a-flask-application-around-an-already-existing-database">here</a>, 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).  </p>
  
  <p>The model.py I set up from the example above results in </p>
  
  <p><strong>EDIT</strong>  I pulled the line </p>
  
  <pre><code> db.Model.metadata.reflect[db.engine]
  </code></pre>
  
  <p>from another post, and it should be db.Model.metadata.reflect(db.engine)
  very simple solution</p>
  
  <p><strong>here is my model.py</strong></p>
  
  <pre><code>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...
  </code></pre>
  
  <p>i get this</p>
  
  <pre><code>&gt;&gt;&gt; from app import db, models
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "app/__init__.py", line 69, in &lt;module&gt;
      from app import views, models
    File "app/views.py", line 1, in &lt;module&gt;
      from app import app,models, db
    File "app/models.py", line 163, in &lt;module&gt;
      db.Model.metadata.reflect[db.engine]
  TypeError: 'instancemethod' object has no attribute '__getitem__'
  </code></pre>
  
  <p><strong>Here's my config.py</strong></p>
  
  <pre><code>SQLALCHEMY_DATABASE_URI = 'postgresql://chet@localhost/ubuntuweb'
  
  SQLALCHEMY_BINDS = {
      'chet':        'postgresql://chet@localhost/warehouse',
   }
  </code></pre>
  
  <p><strong>here's my init.py file</strong></p>
  
  <pre><code>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)
  </code></pre>