scoped_session object has no attribute 'create_all'

5.2k views Asked by At

I have the following code that sets up my database with Flask-SQLAlchemy. I'm getting an exception "AttributeError: scoped_session object has no attribute 'create_all'". Can someone please explain to me why I'm getting the error and how I can fix it? :)

__init__.py:

from flask import Flask

app = Flask(__name__)
from app.db import DB

database = DB()
database.create_all()

db/__init__.py:

from flask import session
from flask.ext.sqlalchemy import SQLAlchemy
from app import app

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:pass@dburl:/schema'
connection = SQLAlchemy(app)

from app.db.models import *

class DB():
    def __init__(self):
         pass

    def create_all(self):
        connection.session.create_all()
        connection.session.commit()
        print("done")

models.py:

from app.db import connection as db

class Test(db.Model):
    __tablename__ = 'Test'

    id = db.Column("ID", db.Integer, primary_key=True)
    name = db.Column("Name", db.String(100), nullable=False)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Test: %s>' % self.name

Any guidance would be greatly appreciated!

1

There are 1 answers

0
davidism On BEST ANSWER

It's connection.create_all(), you added session in the middle.


Unrelated to the immediate problem, there are other things that don't look right.

  • You don't need to commit after running create_all.
  • The extension instance is usually named db. The DB class does nothing, just write your create_all function on its own.
  • You don't need to specify table or column names for Flask-SQLAlchemy models in most cases, and upper case names are not generally used.
  • Don't use tabs, PEP 8 recommends 4 spaces.