简体   繁体   English

RuntimeError:未找到应用程序。 在视图 function 内工作或推送应用程序上下文。 FLASK SQLAlchemy 错误

[英]RuntimeError: No application found. Either work inside a view function or push an application context. FLASK SQLAlchemy error

application.py应用程序.py

from flask import Flask, render_template
from wtform_fields import *
from models import *
app = Flask(__name__)
app.secret_key='REPLACE LATER'
app.config['SQLALCHEMY_DATABASE_URI']='*db link*'
db = SQLAlchemy(app)
@app.route("/", methods=['GET', 'POST'])
def index():

    reg_form = RegistrationForm()

    # Update database if validation success
    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data
        user_object = User.query.filter_by(username=username).first()
        if user_object:
         return "Already Taken"
        user =User(username=username,password=password)
        db.session.add(user)
        db.session.commit()
        return "Inserted into DB"
    return render_template("index.html", form=reg_form)
if __name__ == "__main__":
    app.run(debug=True)

models.py模型.py

from flask_sqlalchemy import SQLAlchemy 
db = SQLAlchemy()
class User(db.Model):
    """ User model """
    __tablename__="users"
    id=db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25) , unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)
    db.create_all()

I am getting this error:我收到此错误:

D:\PostgreSQL\12\bin\GSTChat\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1094, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "D:\PostgreSQL\12\bin\GSTChat\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1071, in _execute_for_all_tables
    app = self.get_app(app)
  File "D:\PostgreSQL\12\bin\GSTChat\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1042, in get_app
    raise RuntimeError(
**RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.**

I even looked for solution in the documentation but, I am not able to resolve the error.我什至在文档中寻找解决方案,但是我无法解决该错误。

EDIT: Adding another answer...编辑:添加另一个答案...

You can have it as you already do in the models.py file, and initialize it later in your application file:您可以像在 models.py 文件中一样拥有它,然后在您的应用程序文件中对其进行初始化:

application.py应用程序.py

from flask import Flask, render_template
from wtform_fields import *
from models import *

app = Flask(__name__)
# Other code you have
db.init_app(app)

Answer 2: I see you are defining db in your application.py file, and again in your models.py file.答案 2:我看到您在 application.py 文件中定义 db,然后在 models.py 文件中再次定义。 You should import it from your app in your models file.您应该从您的应用程序中将其导入模型文件中。

models.py模型.py

from flask_sqlalchemy import SQLAlchemy
from app import db

class User(db.Model):
    """ User model """
    __tablename__="users"
    id=db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25) , unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)

I hope this is helpful and solves your error: :) You may also want to put the db.create_all() in your application.py file (after importing models), instead of in a model itself.我希望这会有所帮助并解决您的错误::) 您可能还希望将db.create_all()放在 application.py 文件中(在导入模型之后),而不是放在 model 本身中。 Cheers.干杯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有蓝图的 Flask-sqlalchemy - 运行时错误:找不到应用程序。 在视图函数中工作或推送应用程序上下文 - Flask-sqlalchemy with Blueprints - RuntimeError: No application found. Either work inside a view function or push an application context Flask - 运行时错误:找不到应用程序。 在视图函数内工作或推送应用程序上下文 - Flask - RuntimeError: No application found. Either work inside a view function or push an application context 试图删除 flask 中的所有表,运行时错误:未找到应用程序。 在视图 function 内工作或推送应用程序上下文 - Trying to drop all tables in flask, RuntimeError: No application found. Either work inside a view function or push an application context Flask、concurrent.futures 和 SQLAlchemy - 找不到应用程序:在视图函数内工作或推送应用程序上下文 - Flask, concurrent.futures and SQLAlchemy - No application found: work inside a view function or push an application context 运行时错误:在应用程序上下文之外工作。 在我的烧瓶应用程序中 - RuntimeError: Working outside of application context. in my flask app 运行时错误:在应用程序上下文之外工作。 烧瓶 - 邮件 - RuntimeError: Working outside of application context. Flask - Mail Flask `RuntimeError:在应用程序上下文之外工作。` 来自中间件 - Flask `RuntimeError: Working outside of application context.` from Middleware 如何修复“RuntimeError:在应用程序上下文之外工作。” 使用 Flask 创建蓝图时? - How to fix "RuntimeError: Working outside of application context." when creating blueprints with Flask? 在应用程序上下文之外工作。 (Python:Flask 错误!) - Working outside of application context. (Python: Flask error!) Flask 测试 - 尝试使用 SQLAlchemy 连接数据库时出现“RuntimeError: No application found” - Flask testing - "RuntimeError: No application found” when trying to connect with db with SQLAlchemy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM