title: Flask: application unable to run because of KeyError
body: <p>Am currently studying how to develop web applications using <code>Flask</code> and i was following <a href="https://damyanon.net/tags/flask/" rel="nofollow noreferrer">this</a> tutorial on how to do it and everything was moving on fine till the concept of Flask-SQLAchemy got introduced.</p>
  
  <p>The structure of my flask application is as below</p>
  
  <pre><code>├── bin
  ├── bookshelf
  │   ├── admin
  │   │   ├── controllers.py
  │   │   ├── __init__.py
  │   ├── data
  │   │   ├── __init__.py
  │   │   ├── models.py
  │   ├── __init__.py
  │   ├── main
  │   │   ├── controllers.py
  │   │   ├── __init__.py
  │   ├── static
  │   └── templates
  ├── config.py
  ├── data-dev.sqlite
  ├── docs
  ├── requirements.txt
  ├── run.py
  </code></pre>
  
  <p>Am trying to use an sqlite database(<code>data-dev.sqlite</code>) that i designed myself without having to go through the process of <code>SQLAchemy</code> creating for me one and below is it's structure; that was generated using the <code>.dump</code> command in sqlite</p>
  
  <pre><code>PRAGMA foreign_keys=OFF;
  BEGIN TRANSACTION;
  CREATE TABLE author (
  id INTEGER NOT NULL PRIMARY KEY,
  author_names VARCHAR(100) NOT NULL UNIQUE
  );
  CREATE TABLE book (
  id INTEGER NOT NULL PRIMARY KEY,
  title VARCHAR(80) NOT NULL,
  rating INT,
  image VARCHAR(30),
  author_id INTEGER NOT NULL,
  FOREIGN KEY (author_id) REFERENCES author(id)
  );
  CREATE TABLE role (
  id INTEGER NOT NULL PRIMARY KEY,
  role_name VARCHAR(80) NOT NULL UNIQUE,
  description VARCHAR(255)
  );
  CREATE TABLE user (
  id INTEGER NOT NULL PRIMARY KEY,
  email VARCHAR(75) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  active BOOLEAN NOT NULL DEFAULT 0,
  role_id INTEGER NOT NULL,
  FOREIGN KEY (role_id) REFERENCES role(id)
  );
  COMMIT;
  </code></pre>
  
  <p>The traceback produced when i run the command <code>python run.py runserver -d</code> in the <code>venv</code> is</p>
  
  <pre><code>Traceback (most recent call last):
    File "run.py", line 1, in &lt;module&gt;
      from bookshelf import create_app
    File "/home/mayatsa/environments/flask-test/bookshelf/__init__.py", line 2, in &lt;module&gt;
      from bookshelf.main.controllers import main
    File "/home/mayatsa/environments/flask-test/bookshelf/main/controllers.py", line 2, in &lt;module&gt;
      from bookshelf.data.models import Author, Book
    File "/home/mayatsa/environments/flask-test/bookshelf/data/models.py", line 6, in &lt;module&gt;
      class Book(db.Model):
    File "/home/mayatsa/environments/flask-test/bookshelf/data/models.py", line 8, in Book
      __table__ = db.Model.metadata.tables['book']
  KeyError: 'book'
  </code></pre>
  
  <p>Files order of traceback from top to bottom and their contents are as follows</p>
  
  <p><strong>run.py</strong></p>
  
  <pre><code>from bookshelf import create_app
  from flask_script import Manager
  
  app = create_app()
  manager = Manager(app)
  
  if __name__ == '__main__':
      manager.run()
  </code></pre>
  
  <p><strong>bookshelf/__init__.py</strong></p>
  
  <pre><code>from flask import Flask
  from bookshelf.main.controllers import main
  from bookshelf.admin.controllers import admin
  from bookshelf.data.models import db
  
  def create_app():
      app = Flask(__name__)
      app.config.from_object('config')
  
      with app.app_context():
          db.init_app(app)
          db.Model.metadata.reflect(db.engine)
  
      app.register_blueprint(main, url_prefix='/')
      app.register_blueprint(admin, url_prefix='/admin')
  
      return app
  </code></pre>
  
  <p><strong>bookshelf/main/controllers.py</strong></p>
  
  <pre><code>from flask import Blueprint, render_template, request
  from bookshelf.data.models import Author, Book
  
  main = Blueprint('main', __name__, template_folder='templates')
  
  @main.route('/')
  def index():
      return render_template('main/index.html')
  
  @main.route('books/')
  def display_books():
      return render_template('main/books.html')
  </code></pre>
  
  <p><strong>bookshelf/data/models.py</strong></p>
  
  <pre><code>from flask_sqlalchemy import SQLAlchemy
  
  db = SQLAlchemy()
  
  class Book(db.Model):
      __table__ = db.Model.metadata.tables['book']
      def __repr__(self):
          return '&lt;Book %r&gt;' % (self.title)
  
  class Author(db.Model):
      __table__ = db.Model.metadata.tables['author']
      def __repr__(self):
          return '&lt;Author %r&gt;' % (self.author_names)
  
  class Role(db.Model):
      __table__ = db.Model.metadata.tables['role']
      def __repr__(self):
          return '&lt;Role %r&gt;' % (self.role_name)
  
  class User(db.Model):
      __table__ = db.Model.metadata.tables['user']
  
      def __repr__(self):
          return '&lt;User %r&gt;' % (self.email)
  </code></pre>
  
  <p>Additional <strong>config.py</strong></p>
  
  <pre><code>import os
  basedir = os.path.abspath(os.path.dirname(__file__))
  
  DEBUG = True
  TESTING = False
  SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
      'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
  SQLALCHEMY_COMMIT_ON_TEARDOWN = True
  SQLALCHEMY_TRACK_MODIFICATIONS = False
  SECRET_KEY = 'a9eec0e0-23b7-4788-9a92-318347b9a39f'
  </code></pre>
  
  <p>From all the code provided above, what could be causing my application to produce this error and stopping it from running?
  Thank you</p>