0

Much is written about creating self-contained functions for other tasks,

but none address how to do so for GET requests.

Considering the following MWE -- how might this be transformed into a self-contained class?

import aiohttp
import asyncio
import time

async def get_pokemon(session, url):
    async with session.get(url) as resp:
        pokemon = await resp.json()
        return pokemon['name']

async def main():
    async with aiohttp.ClientSession() as session:

        tasks = []
        for number in range(1, 151):
            url = f'https://pokeapi.co/api/v2/pokemon/{number}'
            tasks.append(asyncio.ensure_future(get_pokemon(session, url)))

        original_pokemon = await asyncio.gather(*tasks)
        for pokemon in original_pokemon:
            print(pokemon)

asyncio.run(main())

Code credit: https://www.twilio.com/blog/asynchronous-http-requests-in-python-with-aiohttp

python_user
  • 5,375
  • 2
  • 13
  • 32
John Stud
  • 1,506
  • 23
  • 46
  • 2
    What are you having trouble with exactly? Other than turning these functions into `async` methods, what do you need it to do that you're not sure how to do? – Grismar Oct 08 '21 at 03:05
  • Main() cannot be called from a class. – John Stud Oct 08 '21 at 03:09
  • 1
    Of course it can. Any function can be called from anywhere as long as its name is in scope. `class CallMain: async def a_function(self): await main()` – Paul Cornelius Oct 08 '21 at 06:03

0 Answers0