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!
It's
connection.create_all()
, you addedsession
in the middle.Unrelated to the immediate problem, there are other things that don't look right.
create_all
.db
. TheDB
class does nothing, just write yourcreate_all
function on its own.