0

I'm trying to split out my models into a separate file as it's getting too large to manage. I've followed this but I am getting a NameError despite having run db.create_all():

NameError: name 'importsTable' is not defined

# stack_app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from stack_dbmodels import db
from stack_dbmodels import importsTable
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'secretsquirrel'

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stack_newAppCsv.db'
db.init_app(app)

@app.route('/', methods=['GET'])
def stack():
    username = "username"
    new_user = importsTable(username)
    db.session.add(new_user)
    db.session.commit()
    return "Done!"

if __name__ == "__main__":
    app.run(debug = True, port=8080)

My models file:

# stack_dbmodels.py
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class importsTable(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80))

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

    def __repr__(self):
        return '<Import {0}>'.format(self.username)
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50

1 Answers1

0

The problem was mainly with the context of the app but during my tests there were a couple of gotchas I found. Key to make the above work was:

When I reference importsTable it wasn't initially defined unless I did:

from stack_dbmodels import db
from stack_dbmodels import importsTable

And whilst the .db file was created, the context wasn't correct so it couldn't create the actual importsTable so I added the following and problem solved, the key bit was "with app.app_context()":

db.init_app(app)
with app.app_context():
    db.create_all()

Final working code was:

# stack_app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from stack_dbmodels import db
from stack_dbmodels import importsTable
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'secretsquirrel'

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stack_newAppCsv.db'
db.init_app(app)
with app.app_context():
    db.create_all()

@app.route('/', methods=['GET'])
def stack():
    username = "username"
    new_user = importsTable(username)
    db.session.add(new_user)
    db.session.commit()
    return "Done!"

if __name__ == "__main__":
    app.run(debug = True, port=8080)
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50