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
This commit is contained in:
Luna 2020-07-29 18:42:28 -03:00
parent bdf7d875ba
commit 88d6a19415
2 changed files with 13 additions and 5 deletions

View File

@ -20,12 +20,19 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
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,8 +58,8 @@ 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:
async with self.context_function():
return await coro
task = self.loop.create_task(self._wrapper(_ctx_wrapper_bg()))

2
run.py
View File

@ -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):