'没有找到应用程序.要么在视图函数内工作,要么推送应用程序上下文. [英] 'No application found. Either work inside a view function or push an application context.'

查看:32
本文介绍了'没有找到应用程序.要么在视图函数内工作,要么推送应用程序上下文.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 Flask-SQLAlchemy 模型分成单独的文件.当我尝试运行 db.create_all() 时,我得到 No application found.要么在视图函数中工作,要么推送应用程序上下文.

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)

推荐答案

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

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

这篇关于'没有找到应用程序.要么在视图函数内工作,要么推送应用程序上下文.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆