Flask0.10 mongo,在应用范围外工作

2024-05-10 15:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道对于如何处理flask“在应用程序上下文之外工作”几乎没有问题,但我无法让它们为我工作

我有一个长时间运行的mongo聚合查询,计划使用apscheduler定期运行。 下面是我的应用程序结构,但是任务失败,出现“RuntimeError:working outside of application context”。ihttp://flask.pocoo.org/docs/patterns/sqlite3/有一些使用新flask.g的例子,但是想知道是否有人可以建议如何正确地全局保存mongodb连接并在apscheduler中共享该连接

__init.py__

from app import create_app

应用程序.py

from flask import Flask, request, render_template,g
from .extention import mongo, redis, sched

def create_app(config=None):
"""Create a Flask app."""

    app = Flask(__name__)
    configure_extensions(app)
    return app

def configure_extensions(app):
    mongo.init_app(app) # initialise mongo connection from the config
    redis.init_app(app)

from schedule_tasks import *

扩展.py

from flask.ext.pymongo import PyMongo
mongo = PyMongo()

from apscheduler.scheduler import Scheduler
config = {'apscheduler.jobstores.file.class': 'apscheduler.jobstores.shelve_store:ShelveJobStore',
          'apscheduler.jobstores.file.path': '/tmp/sched_dbfile'}
sched = Scheduler(config)

from flask.ext.redis import Redis
redis = Redis()

计划任务.py

from .extention import mongo
@sched.interval_schedule(minutes=1)
def long_running_queries():
    ## mongo agg query ##
    mongo.db.command("aggregate", "collection", pipeline = "some query" )
sched.start()
sched.print_jobs()

Tags: frompyimportredisconfigapp应用程序flask
1条回答
网友
1楼 · 发布于 2024-05-10 15:44:55

要理解此错误,您需要理解application context

对于某人来说,完全有可能编写多个Flask应用程序,所有这些应用程序都在同一进程中处理他们的请求。文档give the following example...

from werkzeug.wsgi import DispatcherMiddleware
from frontend_app import application as frontend
from backend_app import application as backend

application = DispatcherMiddleware(frontend, {
    '/backend':     backend
})

请记住,在这种情况下,前端应用程序可以使用不同的Mongo设置,但使用完全相同的Mongo扩展对象。因此,Flask不能在运行脚本时假设哪个是“当前”应用程序。因此,像url_for(),或者像MongoDB扩展那样的扩展上的许多方法,在它们做任何事情之前,都需要知道哪个应用程序是“当前”的。

因此,当您试图使用Flask或扩展函数来执行除设置应用程序本身(配置值等)以外的任何操作时,您需要显式地告诉Flask当前要分配给application context的应用程序是什么。

医生给了你一种方法。。

# Be careful about recursive imports here
from . import app
from .extention import mongo

@sched.interval_schedule(minutes=1)
def long_running_queries():
    with app.app_context():
        mongo.db.command("aggregate", "collection", pipeline = "some query" )

因此,您需要创建app对象本身,然后使用with app.app_context()行。在with语句中,您的所有调用(例如那些到您的Mongo扩展的调用)都应该可以工作。注意,您不需要在视图中执行这些操作,因为Flask将自动执行所有这些操作,作为处理请求的一部分。

相关问题 更多 >