i know there are few question on how to deal with flask "working outside of application context", but i could not get them to work for me
I have a long running mongo aggregation queries and are scheduled to run at regular intervals using apscheduler. Below is my app structure, but the tasks fail with "RuntimeError: working outside of application context". ihttp://flask.pocoo.org/docs/patterns/sqlite3/ has some example on using the new flask.g but wondering if anyone can advise on how to properly save mongodb connection globally and share that connection in apscheduler
__init.py__
from app import create_app
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 *
extention.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()
schedule_tasks.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()