简体   繁体   English

带有蓝图的 Flask-sqlalchemy - 运行时错误:找不到应用程序。 在视图函数中工作或推送应用程序上下文

[英]Flask-sqlalchemy with Blueprints - RuntimeError: No application found. Either work inside a view function or push an application context

There are a lot of questions regarding this but none of them are using Flask Blueprints.有很多关于此的问题,但没有一个使用 Flask 蓝图。

I am trying to set up a QuerySelectField with a sqlite3 lookup.我正在尝试使用 sqlite3 查找设置 QuerySelectField。 But I get then error:但我得到了错误:

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

Here is my application structure:这是我的应用程序结构: 在此处输入图片说明

My init .py我的初始化.py

from flask import Flask, render_template, current_app
from flask_mail import Mail
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_ckeditor import CKEditor
from instance.config import app_config
from app.views.ticket import ticket as ticket_blueprint
from app.views.users import users as user_blueprint
from app.views.main import main as main_blueprint
from app.models import User, db

login_manager = LoginManager()

def page_not_found(e):
    return render_template('404.html'), 404


def register_blueprints_on_app(app):
    app.register_blueprint(user_blueprint)
    app.register_blueprint(ticket_blueprint)
    app.register_blueprint(main_blueprint)


def login_manager_init(app):
    login_manager.login_view = 'users.login'
    login_manager.init_app(app)


# associate id in the cookie with the User object
@login_manager.user_loader
def load_user(user_id):
    print(user_id)
    return User.query.get(user_id)


# application factory
def create_app(config):
    # create application instance
    app = Flask(__name__, instance_relative_config=True)
    app.register_error_handler(404, page_not_found)
    app.config.from_object(app_config[config])
    app.config.from_pyfile('config.py')

    Bootstrap(app)

    mail = Mail()
    mail.init_app(app)
    db.init_app(app)

    ckeditor = CKEditor()
    ckeditor.init_app(app)

    login_manager_init(app)
    register_blueprints_on_app(app)

    return app

And here is the problematic forms.py which is under ticket/views/这是有问题的 forms.py,它位于 ticket/views/ 下

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField, FieldList, DateTimeField, SelectField
from wtforms_sqlalchemy.fields import QuerySelectField
from wtforms.fields.html5 import EmailField, TelField
from wtforms.validators import InputRequired, Email
from flask_ckeditor import CKEditorField
from app.models import User


def user_query():
    query = User.query()
    return query


class TicketForm(FlaskForm):
    requested_by = QuerySelectField(label='Requested by',
                                    query_factory=user_query(),
                                    allow_blank=False,
                                    get_label='fullname')
    department = SelectField(label='Department')
    phone = TelField(label='Phone')
    email = EmailField(label='Email', validators=[Email('Enter a valid email address')])
    short_desc = StringField(label='Short Description', validators=[InputRequired('Must enter a short description')])
    description = CKEditorField(label='Description')
    classification = StringField(label='Classification')
    priority = StringField(label='Priority')

    sla_respond_by = DateTimeField(label='Respond by', render_kw={'readonly': True})
    sla_resolve_by = DateTimeField(label='Resolve by', render_kw={'readonly': True})
    sla_status = StringField(label='SLA Status', render_kw={'readonly': True})

    related_tickets = FieldList(StringField(label='Ticker #'))
    client_journal = TextAreaField(label='Client Area')
    work_notes = TextAreaField(label='Work Notes')
    closed_at = DateTimeField(label='Closed')
    closed_by = StringField(label='Closed by')
    followed_by = StringField(label='Followed by')
    submit = SubmitField('Save')

The problem part is when this runs问题部分是什么时候运行

 def user_query():
        query = User.query()
        return query

I get the error.我得到了错误。

For context here is the routes file under ticket/view这里的上下文是票证/视图下的路由文件

from flask import render_template
from app.views.ticket.forms import TicketForm
from flask_login import login_required
from . import ticket


@ticket.get('/ticket')
@ticket.put('/ticket')
@login_required
def ticket():
    form = TicketForm()
    return render_template('ticket.html', form=form)

And in ticket/view/ init .py并在票证/视图/ init .py

from flask import Blueprint

ticket = Blueprint('ticket', __name__, static_folder='static', template_folder='templates')

from . import routes

I read the doc here but it was no help.我在这里阅读了文档,但没有帮助。 https://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/ https://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/

I can't work out how to pass the application context so this function works.我无法弄清楚如何传递应用程序上下文以使此函数起作用。

I got around this by not using a query_factory in the QuerySelectfield.我通过在 QuerySelectfield 中不使用 query_factory 来解决这个问题。

I changed the field declaration from this:我从此更改了字段声明:

class TicketForm(FlaskForm):
    requested_by = QuerySelectField(label='Requested by',
                                    query_factory=user_query(),
                                    allow_blank=False,
                                    get_label='full_name')

To this:对此:

class TicketForm(FlaskForm):
    requested_by = QuerySelectField(label='Requested by',
                                    allow_blank=False,
                                    get_label='full_name')

(so, just removed query_factory=user_query(),) (所以,刚刚删除了 query_factory=user_query(),)

I deleted this:我删除了这个:

def user_query():
        query = User.query()
        return query

Then added this to the route in my Blueprint:然后将其添加到我的蓝图中的路线中:

@ticket.get('/ticket')
@ticket.put('/ticket')
@login_required
def ticket():
    form = TicketForm()

    form.requested_by.query = User.query.all()  # Added this

    print(current_app.app_context())
    return render_template('ticket.html', form=form)

I hope that helps someone as it was doing my head in. I'd still like to know how to do it the other way with a query_factory as I'm sure there is a way.我希望这对我的头脑有所帮助。我仍然想知道如何使用 query_factory 以另一种方式做到这一点,因为我确定有一种方法。 So if anyone knows please share!所以如果有人知道请分享!

暂无
暂无

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

相关问题 RuntimeError:未找到应用程序。 在视图 function 内工作或推送应用程序上下文。 FLASK SQLAlchemy 错误 - RuntimeError: No application found. Either work inside a view function or push an application context. FLASK SQLAlchemy error 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 Flask,将 Flask-sqlalchemy 的应用程序上下文推送到 huey worker - Flask, push application context for Flask-sqlalchemy to huey worker Flask-SQLAlchemy db.create_all() 在应用程序上下文之外引发 RuntimeError - Flask-SQLAlchemy db.create_all() raises RuntimeError working outside of application context Flask-SQLAlchemy 找不到应用程序运行时错误 - Flask-SQLAlchemy No Application Found Runtime Error 使用Flask-SQLAlchemy反映表会引发RuntimeError:应用程序未注册 - Reflecting tables with Flask-SQLAlchemy raises RuntimeError: application not registered 如何让 Flask-SQLAlchemy 使用应用程序工厂模式 - How to get Flask-SQLAlchemy to work with the Application Factory Pattern 如何修复“RuntimeError:在应用程序上下文之外工作。” 使用 Flask 创建蓝图时? - How to fix "RuntimeError: Working outside of application context." when creating blueprints with Flask?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM