From 88d6a19415a737298b4dd0df2c9a244ecbcc4b83 Mon Sep 17 00:00:00 2001 From: Luna Date: Wed, 29 Jul 2020 18:42:28 -0300 Subject: [PATCH] don't use copy_current_app_context in some scenarios, the app context might not be there yet, it's easier to use the global app instance and embed it in JobManager instead --- litecord/jobs.py | 16 ++++++++++++---- run.py | 2 +- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/litecord/jobs.py b/litecord/jobs.py index 4f08271..44342e1 100644 --- a/litecord/jobs.py +++ b/litecord/jobs.py @@ -20,12 +20,19 @@ along with this program. If not, see . import asyncio from typing import Any -from quart.ctx import copy_current_app_context from logbook import Logger log = Logger(__name__) +class EmptyContext: + async def __aenter__(self): + pass + + async def __aexit__(self, _typ, _value, _traceback): + pass + + class JobManager: """Background job manager. @@ -34,8 +41,9 @@ class JobManager: its own internal list of jobs. """ - def __init__(self, loop=None): + def __init__(self, *, loop=None, context_func=None): self.loop = loop or asyncio.get_event_loop() + self.context_function = context_func or EmptyContext self.jobs = [] async def _wrapper(self, coro): @@ -50,9 +58,9 @@ class JobManager: def spawn(self, coro): """Spawn a given future or coroutine in the background.""" - @copy_current_app_context async def _ctx_wrapper_bg() -> Any: - return await coro + async with self.context_function(): + return await coro task = self.loop.create_task(self._wrapper(_ctx_wrapper_bg())) self.jobs.append(task) diff --git a/run.py b/run.py index 0ecc74f..9f4ab10 100644 --- a/run.py +++ b/run.py @@ -252,7 +252,7 @@ async def init_app_db(app_): log.info("db connect") app_.db = await asyncpg.create_pool(**app.config["POSTGRES"]) - app_.sched = JobManager() + app_.sched = JobManager(context_func=app.app_context) def init_app_managers(app_: Quart, *, init_voice=True):