'No application found. Either work inside a view function or push an application context.' [duplicate]

一个人想着一个人 提交于 2020-01-09 09:56:29

问题


I'm trying to separate my Flask-SQLAlchemy models into separate files. When I try to run db.create_all() I get 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:


Use with app.app_context() to push an application context when creating the tables.

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

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


来源:https://stackoverflow.com/questions/46540664/no-application-found-either-work-inside-a-view-function-or-push-an-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!