cake-erp-challenge/api/util/fetch.py

49 lines
1.6 KiB
Python
Raw Normal View History

2021-10-18 15:49:47 -04:00
from api.models.trainer import Trainer
import requests
import json
class NotFound(Exception):
2021-10-18 23:26:16 -04:00
def __init__(self, message):
self.message = message
2021-10-18 15:49:47 -04:00
def get_or_not_found(callback):
2021-10-18 15:49:47 -04:00
try:
resource = callback()
if resource is None:
2021-10-18 23:26:16 -04:00
raise NotFound("Resource not found")
return resource
2021-10-18 15:49:47 -04:00
except:
2021-10-18 23:26:16 -04:00
raise NotFound("Resource not found")
def get_trainer_fail(id):
return get_or_not_found(lambda : Trainer.query.get(id))
2021-10-18 15:49:47 -04:00
def get_trainer_by_nick_fail(nickname):
return get_or_not_found(lambda : Trainer.query.filter_by(nickname=nickname).one())
def get_pokemon_fail(trainer, id):
return get_or_not_found(lambda : trainer.pokemons_list.filter_by(id=id).one())
2021-10-18 15:49:47 -04:00
2021-10-18 23:43:26 -04:00
# helper interno
2021-10-18 23:26:16 -04:00
def cant_fetch_error(pokemon):
raise NotFound("Could not fetch data for pokemon with id {}".format(pokemon.pokemon_id))
2021-10-18 15:49:47 -04:00
# seguintes funções puxam informações da pokeapi
def set_pokemon_data(pokemon):
try:
response = requests.get("https://pokeapi.co/api/v2/pokemon/{}".format(pokemon.pokemon_id))
if response.status_code != 200:
2021-10-18 23:26:16 -04:00
cant_fetch_error(pokemon)
pokemon.pokemon_data = json.loads(response.text)
except:
2021-10-18 23:26:16 -04:00
cant_fetch_error(pokemon)
2021-10-18 15:49:47 -04:00
async def async_set_pokemon_data(session, pokemon):
try:
response = await session.get("https://pokeapi.co/api/v2/pokemon/{}".format(pokemon.pokemon_id))
if response.status != 200:
2021-10-18 23:26:16 -04:00
cant_fetch_error(pokemon)
pokemon.pokemon_data = json.loads(await response.text())
except:
2021-10-18 23:26:16 -04:00
cant_fetch_error(pokemon)