|
| 1 | +""" |
| 2 | + EJERCICIO: |
| 3 | + Utilizando un mecanismo de peticiones HTTP de tu lenguaje, realiza |
| 4 | + una petición a la web que tú quieras, verifica que dicha petición |
| 5 | + fue exitosa y muestra por consola el contenido de la web. |
| 6 | +
|
| 7 | + DIFICULTAD EXTRA (opcional): |
| 8 | + Utilizando la PokéAPI (https://pokeapi.co), crea un programa por |
| 9 | + terminal al que le puedas solicitar información de un Pokémon concreto |
| 10 | + utilizando su nombre o número. |
| 11 | + - Muestra el nombre, id, peso, altura y tipo(s) del Pokémon |
| 12 | + - Muestra el nombre de su cadena de evoluciones |
| 13 | + - Muestra los juegos en los que aparece |
| 14 | + - Controla posibles errores |
| 15 | +""" |
| 16 | +import requests |
| 17 | + |
| 18 | + |
| 19 | +print(f"## Explicación {'#' * 30}\n") |
| 20 | +print(r""" |
| 21 | +El módulo "requests" permite hacer envío y recepción de solicitudes HTML a través de métodos GET, POST, PUT y DELETE. |
| 22 | +Para el caso, vamos a usat "get" para consumir una API que nos entregará una cantidad "c" de palabras en español (útil, |
| 23 | +por ejemplo, para hacer una partida de "ahoracado" -o adivina la palabra-). |
| 24 | +
|
| 25 | +Es importante conocer qué estaría devolviendo la API para poder explotarla correctamente (viendo la doc específica o |
| 26 | +usando herramientas como "postman" o, si no, yendo a la "url" y ver qué trae). |
| 27 | +
|
| 28 | +import requests |
| 29 | +
|
| 30 | +response = requests.get(url="https://clientes.api.greenborn.com.ar/public-random-word", params={"c": 10}, timeout=5) |
| 31 | +status = response.status_code |
| 32 | +if status == 200: |
| 33 | + palabras = response.json() |
| 34 | + print(f"Palabras para usar: {palabras}") |
| 35 | +else: |
| 36 | + print(f"Error HTTP: {status}") |
| 37 | +""") |
| 38 | +response = requests.get(url="https://clientes.api.greenborn.com.ar/public-random-word", params={"c": 10}, timeout=5) |
| 39 | +status = response.status_code |
| 40 | +if status == 200: |
| 41 | + palabras = response.json() |
| 42 | + print(f"Palabras para usar: {palabras}", end="\n\n") |
| 43 | +else: |
| 44 | + print(f"Error HTTP: {status}", end="\n\n") |
| 45 | + |
| 46 | +print(f"## Dificultad extra {'#' * 30}") |
| 47 | + |
| 48 | +URL_BASE = "https://pokeapi.co/api/v2/" |
| 49 | + |
| 50 | + |
| 51 | +def query_api(url: str, params=None) -> dict: |
| 52 | + data = dict() |
| 53 | + try: |
| 54 | + req = requests.get(url, params, timeout=2) |
| 55 | + if req.status_code == 200: |
| 56 | + data = req.json() |
| 57 | + else: |
| 58 | + print(f"{url} devolvió RC={req.status_code}") |
| 59 | + except requests.exceptions.Timeout: |
| 60 | + print(f"{url} NO respondió a tiempo. Intente más tarde.") |
| 61 | + return data |
| 62 | + |
| 63 | + |
| 64 | +def get_pokemon_id(name: str, count: int) -> str: |
| 65 | + def get_id(url: str) -> str: |
| 66 | + fields = url[:-1].split("/") |
| 67 | + return fields.pop() |
| 68 | + |
| 69 | + data = query_api(URL_BASE + "pokemon/", {"offset": 0, "limit": str(count)}) |
| 70 | + |
| 71 | + for pokemones in data.items(): |
| 72 | + if pokemones[0] == "results": |
| 73 | + for p in pokemones[1]: |
| 74 | + if p['name'].lower() == name.lower(): |
| 75 | + return get_id(p['url']) |
| 76 | + return "" |
| 77 | + |
| 78 | + |
| 79 | +def get_pokemon_data(pok_id: str) -> tuple: |
| 80 | + def pokemon_evol_chain(pok_id: str) -> list: |
| 81 | + evolves_chain = [] |
| 82 | + data = query_api(URL_BASE + "pokemon-species/" + pok_id + "/") |
| 83 | + try: |
| 84 | + evolves_to_url = data["evolution_chain"]["url"] |
| 85 | + evol_to_data = query_api(evolves_to_url) |
| 86 | + evolves_chain.append(evol_to_data["chain"]["species"]["name"]) |
| 87 | + evolves_chain.append(evol_to_data["chain"]["evolves_to"][0]["species"]["name"]) |
| 88 | + evolves_chain.append(evol_to_data["chain"]["evolves_to"][0]["evolves_to"][0]["species"]["name"]) |
| 89 | + except Exception: |
| 90 | + pass |
| 91 | + finally: |
| 92 | + return evolves_chain |
| 93 | + |
| 94 | + games = [] |
| 95 | + data = query_api(URL_BASE + "pokemon/" + pok_id + "/") |
| 96 | + type_ = data["types"][0]["type"]["name"] |
| 97 | + height = data["height"] |
| 98 | + weight = data["weight"] |
| 99 | + for game in data["game_indices"]: |
| 100 | + games.append(game["version"]["name"]) |
| 101 | + form_url = data["forms"][0]["url"] |
| 102 | + form_data = query_api(form_url) |
| 103 | + image_url = form_data["sprites"]["front_default"] |
| 104 | + evolves_chain = pokemon_evol_chain(pok_id) |
| 105 | + return type_, height, weight, games, image_url, evolves_chain |
| 106 | + |
| 107 | + |
| 108 | +def show_profile(name, id_, data): |
| 109 | + print(f""" |
| 110 | + Pokemon name: {name} (id: {id_}) |
| 111 | + Type: {data[0]} |
| 112 | + Height: {data[1]} |
| 113 | + Weight: {data[2]} |
| 114 | + Games: |
| 115 | +""", end="") |
| 116 | + for g in data[3]: |
| 117 | + print(f"\t\t{g}") |
| 118 | + print(f"\tEvolution chain:") |
| 119 | + for ec in data[5]: |
| 120 | + print(f"\t\t{ec}") |
| 121 | + print(f"\tImage: {data[4]}") |
| 122 | + |
| 123 | + |
| 124 | +def main(): |
| 125 | + pokemon = "" |
| 126 | + pokemon_count = 0 |
| 127 | + data = query_api(URL_BASE + "pokemon/", {"offset": 0, "limit": 1}) |
| 128 | + if data: |
| 129 | + pokemon = "_" |
| 130 | + pokemon_count = data["count"] |
| 131 | + while pokemon: |
| 132 | + pokemon = input("\nEnter pokemon name (empty to exit): ") |
| 133 | + pokemon_id = get_pokemon_id(pokemon, pokemon_count) |
| 134 | + if pokemon_id: |
| 135 | + pokemon_data = get_pokemon_data(pokemon_id) |
| 136 | + show_profile(pokemon, pokemon_id, pokemon_data) |
| 137 | + |
| 138 | + |
| 139 | +if __name__ == "__main__": |
| 140 | + main() |
0 commit comments