将外部数据库模型导入Flask App时,为什么会出现NameError?

时间:2018-03-05 12:56:16

标签: python flask-sqlalchemy

我正在尝试将我的模型拆分成一个单独的文件,因为它太大而无法管理。我跟着this但是我得到了一个N​​ameError,尽管已经运行了db.create_all():

  

NameError:未定义名称“importsTable”

# 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)

我的模特档案:

# 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)

1 个答案:

答案 0 :(得分:0)

问题主要在于应用程序的上下文,但在我的测试中,我发现了一些问题。完成上述工作的关键是:

当我引用importsTable时,除非我这样做,否则最初没有定义:

from stack_dbmodels import db
from stack_dbmodels import importsTable

虽然创建了.db文件,但是上下文不正确所以它无法创建实际的importsTable所以我添加了以下内容并解决了问题,关键位是“with app.app_context()”:< / p>

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)