'未找到任何申请。在视图函数内部工作或推送应用程序上下文。'

时间:2017-10-03 08:51:11

标签: python flask flask-sqlalchemy

我试图将我的Flask-SQLAlchemy模型分成单独的文件。当我尝试运行db.create_all()时,我得到No application found. Either work inside a view function or push an application context.

shared/db.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

app.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from shared.db import db

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'My connection string'
db.init_app(app)

user.py

from shared.db import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email_address = db.Column(db.String(300), unique=True, nullable=False)
    password = db.Column(db.Text, nullable=False)

1 个答案:

答案 0 :(得分:31)

使用with app.app_context()推送该块的应用程序上下文。

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'My connection string'

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