Example #1
0
def get_one_swapi(id=None, nome=None):
    n = 1
    output = []
    result = []
    mensagem = {'Erro': 'Nenhum planeta encontrado'}
    #SWAPI
    planets = swapi.get_all("planets")
    for r in planets.order_by("created"):
        output.append({
            '_id': n,
            'nome': r.name,
            'clima': r.climate,
            'terreno': r.terrain,
            'quantidade de aparições em filmes: ': len(r.films)
        })
        n += 1
    if id != None:
        for i in output:
            if i['_id'] == id:
                result.append({
                    '_id':
                    i['_id'],
                    'nome':
                    i['nome'],
                    'clima':
                    i['clima'],
                    'terreno':
                    i['terreno'],
                    'quantidade de aparições em filmes: ':
                    len(swapi.get_planet(i['_id']).films)
                })

    if nome != None:
        for i in output:
            if i['nome'] == nome:
                result.append({
                    '_id':
                    i['_id'],
                    'nome':
                    i['nome'],
                    'clima':
                    i['clima'],
                    'terreno':
                    i['terreno'],
                    'quantidade de aparições em filmes: ':
                    len(swapi.get_planet(i['_id']).films)
                })

    if len(result) == 0:
        return mensagem
    else:
        return result
Example #2
0
def getPLanetByID(self, idPlanet):

    planet = swapi.get_planet(idPlanet)
    print(planet)
    if (planet is None):
        return None

    return planet
Example #3
0
def index():
    # Initialize the context
    context = {"found": False, "search": False}
    qp_term = request.args.get('search_term')
    if request.method == "POST" or qp_term:
        # If a multiple was found, then we need to grab from the query parameter
        # Did you say ‘ex-leper’?
        if qp_term:
            term = qp_term
        else:
            # Grab the client's search term from form
            term = request.form["search_term"]
        # The helper library doesn't have a search function so we'll make the request ourselves.
        search_response = get(
            f"https://swapi.co/api/people/?search={term}").json()
        count = search_response["count"]

        # Only one result returned. That’s right, sir. 16 years behind a veil and proud of it, sir.
        if count == 1:
            person = search_response["results"][0]
            planet = int("".join(n for n in person["homeworld"]
                                 if n.isdigit()))
            homeworld = swapi.get_planet(planet)
            # Population can be a number or "unknown"
            try:
                population = "{0:,d}".format(int(homeworld.population))
            except ValueError:
                population = homeworld.population.title()
            # Create content response to send back to client
            context = {
                "search": True,
                "found": True,
                "name": person["name"],
                "homeworld_name": homeworld.name,
                "homeworld_population": population,
                "homeworld_climate": homeworld.climate,
            }
        # Multiple results returned
        elif 1 < count:
            # Send list of found names to the client
            results = list()
            for r in search_response["results"]:
                results.append(r["name"])
            context = {
                "found": True,
                "search": True,
                "name": term,
                "multiples": results,
                "multiples_count": len(results),
            }
        # No results returned
        elif count < 1:
            context = {"found": False, "search": True, "name": term}

    return render_template("index.html", context=context)
Example #4
0
 def test_repr_(self):
     starship = swapi.get_starship(3)
     self.assertEquals('<Starship - Star Destroyer>', starship.__repr__())
     vehicle = swapi.get_vehicle(4)
     self.assertEquals('<Vehicle - Sand Crawler>', vehicle.__repr__())
     film = swapi.get_film(1)
     self.assertEquals('<Film - A New Hope>', film.__repr__())
     planet = swapi.get_planet(1)
     self.assertEquals('<Planet - Tatooine>', planet.__repr__())
     species = swapi.get_species(1)
     self.assertEquals('<Species - Human>', species.__repr__())
Example #5
0
 def test_repr_(self):
     starship = swapi.get_starship(3)
     self.assertEquals('<Starship - Star Destroyer>', starship.__repr__())
     vehicle = swapi.get_vehicle(4)
     self.assertEquals('<Vehicle - Sand Crawler>', vehicle.__repr__())
     film = swapi.get_film(1)
     self.assertEquals('<Film - A New Hope>', film.__repr__())
     planet = swapi.get_planet(1)
     self.assertEquals('<Planet - Tatooine>', planet.__repr__())
     species = swapi.get_species(1)
     self.assertEquals('<Species - Human>', species.__repr__())
Example #6
0
def gen_dict_info_from_movie(id):

    movie = swapi.get_film(id)
    characters = []
    planets = []
    species = []
    spaceships = []
    vehicles = []
    """ get all characters from a movie and store them """
    for person in movie.characters:
        person_id = person.split('/')[5]
        characters.append((swapi.get_person(person_id)).name)

    #print (characters)
    #print(len(characters))
    """ get all planets from a movie and store them """
    for planet in movie.planets:
        planet_id = planet.split('/')[5]
        planets.append((swapi.get_planet(planet_id)).name)

    #print (planets)
    """ get all species from a movie and store them """
    for specie in movie.species:
        specie_id = specie.split('/')[5]
        species.append((swapi.get_species(specie_id)).name)
    """ get all starships from a movie and store them """
    for spaceship in movie.starships:
        ship_id = spaceship.split('/')[5]
        spaceships.append((swapi.get_starship(ship_id)).name)
    """ get all vehicles from a movie and store them """
    for vehicle in movie.vehicles:
        vehicle_id = vehicle.split('/')[5]
        vehicles.append((swapi.get_vehicle(vehicle_id)).name)

    dict = {
        'title': movie.title,
        'characters': characters,
        'planets': planets,
        'species': species,
        'spaceships': spaceships,
        'vehicles': vehicles
    }
    return dict
Example #7
0
def main():
    search = input(str("Please input a Star Wars character: "))

    data = read_api(search)

    # read in single value attributes
    attributes = ("name", "birth_year", "eye_color", "gender", "hair_color",
                  "height", "mass", "skin_color")
    for x in attributes:
        print(x + ": " + data[x])

    # homeworld
    print("Homeworld: " +
          (swapi.get_planet(get_external(data["homeworld"]))).name)

    # read in multi value attributes
    attributes = ("films", "species", "starships", "vehicles")
    for x in attributes:
        print(x + ":")
        for j in range(0, len(data[x])):
            print("    " + str(get(x, get_external(data[x][j]))))
Example #8
0
def swapi_to_action(text):
    try:
        if get_match(text, 'swapi')[0]:
            index = get_match(text, 'swapi')[1]
            if index == 0:
                i = swapi.get_planet(randint(1, 61))
                print i
            if index == 1:
                i = swapi.get_film(randint(1, 7))
                print i
            if index == 2:
                i = swapi.get_vehicle(randint(1, 39))
                print i
            if index == 3:
                i = swapi.get_starship(randint(1, 37))
                print i
            if index == 4:
                i = wapi.get_specie(randint(1, 37))
                print i
            if index == 5:
                i = swapi.get_person(randint(1, 87))
                print i
    except:
        pass
Example #9
0
 def test_get_person_homeworld(self):
     luke = swapi.get_person(1)
     home = luke.get_homeworld()
     tatooine = swapi.get_planet(1)
     self.assertEquals(type(home), Planet)
     self.assertEquals(home.name, tatooine.name)
Example #10
0
def get_one_swapi(id=None,nome=None): 
    n = 1
    output = []
    result = []
    mensagem = {'Erro':'Nenhum planeta encontrado'}
    #SWAPI
    planets = swapi.get_all("planets")
    for r in planets.order_by("created"):
        output.append({'_id':n,'nome':r.name,'clima':r.climate,'terreno':r.terrain,'quantidade de aparições em filmes: ' : len(r.films)})
        n+=1
    if id != None:
        for i in output:
            if i['_id'] == id:
                result.append({'_id':i['_id'],'nome':i['nome'],'clima':i['clima'],'terreno':i['terreno'],'quantidade de aparições em filmes: ': len(swapi.get_planet(i['_id']).films)})

    if nome != None:
        for i in output:
            if i['nome'] == nome:
                result.append({'_id':i['_id'],'nome':i['nome'],'clima':i['clima'],'terreno':i['terreno'],'quantidade de aparições em filmes: ': len(swapi.get_planet(i['_id']).films)})
    
    if len(result) == 0:
        return mensagem
    else:
        return result
Example #11
0
 def test_planet_get_films(self):
     planet = swapi.get_planet(1)
     self.assertEquals(type(planet.get_films()), FilmQuerySet)
Example #12
0
 def test_get_person_homeworld(self):
     luke = swapi.get_person(1)
     home = luke.get_homeworld()
     tatooine = swapi.get_planet(1)
     self.assertEquals(type(home), Planet)
     self.assertEquals(home.name, tatooine.name)
Example #13
0
 def test_planet_get_residents(self):
     planet = swapi.get_planet(1)
     self.assertEquals(type(planet.get_residents()), PeopleQuerySet)
Example #14
0
        ocL = len(film.opening_crawl)
        tL = len(tweet)
        tot = (ocL if ocL + tL <= 276 else 276 - tL)
        tweet += film.opening_crawl[:tot] + "..."
elif (opc == 2):
    #people
    try:
        person = swapi.get_person(randint(1, 87))
    except:
        person = swapi.get_person(1)
    home = person.get_homeworld()
    tweet = "#StarWars\nPerson\nName: " + person.name + "\nHeight: " + person.height + "\nMass: " + person.mass + "\nHair Color: " + person.hair_color + "\nSkin Color: " + person.skin_color + "\nEye Color: " + person.eye_color + "\nBirth Year: " + person.birth_year + "\nGender: " + person.gender + "\nHomeworld: " + home.name
elif (opc == 3):
    #planets
    try:
        planet = swapi.get_planet(randint(1, 61))
    except:
        planet = swapi.get_planet(1)
    tweet = "#StarWars\nPlanet\nName: " + planet.name + "\nRotation Period: " + planet.rotation_period + "\nOrbital Period: " + planet.orbital_period + "\nDiameter: " + planet.diameter + "\nClimate:" + planet.climate + "\nGravity: " + planet.gravity + "\nTerrain: " + planet.terrain + "\nSurface_water:" + planet.surface_water + "\nPopulation:" + planet.population
elif (opc == 4):
    #starships
    try:
        starship = swapi.get_starship(randint(1, 37))
    except:
        starship = swapi.get_starship(10)
    tweet = "#StarWars\nStarship\nName: " + starship.name + "\nModel: " + starship.model + "\nManufacturer: " + starship.manufacturer + "\nMax Atmosphering Speed: " + starship.max_atmosphering_speed + "\nStarship Class: " + starship.starship_class + "\nCargo Capacity: " + starship.cargo_capacity
elif (opc == 5):
    #vehicles
    try:
        vehicle = swapi.get_vehicle(randint(1, 39))
    except:
Example #15
0
def planet():
    swapi.get_planet(randint(1, 61))
Example #16
0
 def test_planet_get_films(self):
     planet = swapi.get_planet(1)
     self.assertEquals(type(planet.get_films()), FilmQuerySet)
Example #17
0
 def test_planet_get_residents(self):
     planet = swapi.get_planet(1)
     self.assertEquals(type(planet.get_residents()), PeopleQuerySet)