[Python] How to use aiohttp with apscheduler?

Discussão em 'Python' iniciado por Stack, Novembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I would like to fetch several web pages periodically all within the same aiohttp.ClientSession(). Here is what I have got so far. The URLs need to remain within the jobs, because some other URLs will need to be calculated.

    What command is missing in the place of ???. Or do I need to do this in a completely different way? Thanks in advance for your help.

    P.S.: The seconds interval is for testing purposes only. Later, I will change it to a one minute interval.

    from apscheduler.schedulers.asyncio import AsyncIOScheduler
    import asyncio
    import aiohttp

    async def fetch(session, url, timeout=3):
    async with session.get(url, ssl=False, timeout=timeout) as response:
    return await response.text(), response.status

    async def GOESX_job(session):
    url = 'https://services.swpc.noaa.gov/json/goes/primary/xrays-6-hour.json'
    response, status = await fetch(session, url)
    print(status)

    async def GOESp_job(session):
    url = 'https://services.swpc.noaa.gov/json/goes/primary/integral-protons-6-hour.json'
    response, status = await fetch(session, url)
    print(status)

    async def jobs(scheduler):
    async with aiohttp.ClientSession() as session:
    scheduler.add_job(GOESX_job, 'interval', seconds=2, args=[session])
    scheduler.add_job(GOESp_job, 'interval', seconds=3, args=[session])

    scheduler = AsyncIOScheduler()
    ??? jobs(scheduler)

    scheduler.start()
    asyncio.get_event_loop().run_forever()

    Continue reading...

Compartilhe esta Página