0

I am trying to use flask-sqlalchemy to manage my pre-existing mysql database, and I have a table named content. Here is my code snippet.

# coding:utf-8
from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
...

app = Flask(__name__)
bootstrap = Bootstrap(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://...'
db = SQLAlchemy(app)


class Content(db.Model):
    __table__ = db.Model.metadata.tables['content']

    def __repr__(self):
        return '<title %r>' % self.title


@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

...

if __name__ == '__main__':
    app.run(debug=True)

When I run the code above, I get this error

Traceback (most recent call last):
  File "hello.py", line 13, in <module>
    class Content(db.Model):
  File "hello.py", line 14, in Content
    __table__ = db.Model.metadata.tables['content']
KeyError: 'content'

Any help will be appreciated.

ballade4op52
  • 2,142
  • 5
  • 27
  • 42
  • 1
    The `KeyError` shows you accessing the table as `Content` while the code snippet shows you accessing it as `content` - do both ways cause `KeyError`s? – Sean Vieira Apr 10 '15 at 15:16
  • @SeanVieira actually i copied the wrong report , i've modified my question.please check out. –  Apr 10 '15 at 15:28
  • Any reason why you are using `metadata.tables` instead of just using `__table__ = 'content'`? – Sean Vieira Apr 10 '15 at 15:43
  • @SeanVieira I learned from here. http://stackoverflow.com/a/19064993/4144064. –  Apr 10 '15 at 15:59
  • 1
    1. Are you calling `db.Model.metadata.reflect(db.engine)` before you create the model? 2. Does the `content` table already exist in the DB? – Sean Vieira Apr 10 '15 at 16:03
  • @SeanVieira no error report anymore when I call do.Model.metadata.reflect(do.engine). Thanks, SeanVieira. –  Apr 10 '15 at 16:17

1 Answers1

0

Based on this answer you need to call db.Model.metadata.reflect(db.engine) before you create the model. That way the existing table's metadata will be populated in metadata.tables.

Community
  • 1
  • 1
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293