aiohttp's ClientSession using APScheduler's tasks

Viewed 48

So aiohttp recommends using a single ClientSession for the full duration of an application, however if I am using APScheduler to make scheduled requests I am not sure how one would go about passing the ClientSession around to the scheduled jobs...

There is one way that I think can be done but it seems rather 'hacky', so I am not sure if this would mess with some functionality of ClientSession.

# scheduler.py
from apscheduler.jobstores.redis import RedisJobStore  # type: ignore
from apscheduler.schedulers.blocking import AsyncIOScheduler  # type: ignore
from pytz import utc


jobstore = RedisJobStore()
redis = jobstore.redis
scheduler = AsyncIOScheduler()
scheduler.add_jobstore(jobstore)
# tasks.py
from scheduler import scheduler as sched


@sched.scheduled_job('cron', minute=30, args=(sched.session,))
async def task_with_request(session):
    async with session.get('https://someapi.com') as response:
        page = await response.text()
        # Do something with page
# main.py
from scheduler import scheduler as sched


if __name__ == '__name__':
    async with aiohttp.ClientSession() as session:
        sched.session = session
        sched.start()
0 Answers
Related