Python '没有找到应用程序。要么在视图函数内工作,要么推送应用程序上下文。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46540664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:41:17  来源:igfitidea点击:

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

pythonflaskflask-sqlalchemy

提问by Omegastick

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.

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

shared/db.py:

shared/db.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

app.py:

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:

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)

回答by Shtlzut

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

用于with app.app_context()在创建表时推送应用程序上下文。

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

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