def schedule_queries(): # tasks called by celery beat are unfortunatelly outside of app context, so it needs to be added manually with create_app_celery().app_context(): from flask import current_app engine = db.get_engine(current_app) connection = engine.connect() aqs = connection.execute(select([models.AdminQuery]).where(models.AdminQuery.enable_autorun == True)) if aqs.returns_rows: aqs = [{key: value for (key, value) in o.items()} for o in aqs] for aq in aqs: run_admin_query.delay(aq['id'])
def cache_tracker_synset_history(): # tasks called by celery beat are unfortunatelly outside of app context, so it needs to be added manually with create_app_celery().app_context(): paginated_synsets = models.TrackerSynsetsHistory.query.filter( models.TrackerSynsetsHistory.search_by_form_filter('', '', '', '')) cache_key = "sh-count-{}_{}_{}_{}".format('', '', '', '') paginate(paginated_synsets, 1, 50, total_cache_key=cache_key, update=True)
def run_admin_query(key): with create_app_celery().app_context(): models.AdminQuery.results(key, update=True)
def cache_user_activity_yesterday(): # tasks called by celery beat are unfortunatelly outside of app context, so it needs to be added manually with create_app_celery().app_context(): today = time.strftime("%Y-%m-%d", time.gmtime(time.time() - 24*3600)) user_activity_cached(today, '', update=True, timeout=12*3600)
from celery import Celery from tracker.app import blueprints_to_import, create_app_celery, register_blueprints, register_admin try: from flask import current_app # it is necessary to use current_app so that it's evaluated properly (as it is lazy) # and runs the code that raises RuntimeError in case of app not being started yet id(current_app) from celery import current_app as celery except RuntimeError: current_app = create_app_celery() celery = Celery( current_app.import_name, include=list( map(lambda x: "tracker.blueprints.{}.tasks".format(x), blueprints_to_import) ), ) celery.conf.update(current_app.config) class ContextTask(celery.Task): def __call__(self, *args, **kwargs): with current_app.app_context(): return self.run(*args, **kwargs) celery.Task = ContextTask celery.set_default() # registering blueprints must take place when celery is already configured, # because views in blueprints might use imported tasks, which requires them to be already defined register_blueprints(current_app) register_admin(current_app)