def test_queryset_order_by(self): planets = swapi.get_all('planets') ordered = planets.order_by('diameter') self.assertEquals(ordered[0].diameter, '0') people = swapi.get_all('people') ordered = people.order_by('name') self.assertEquals(ordered[0].name, 'Ackbar')
def wrapper(): try: print("Running sanity check...") swapi.get_all("films") print("Sanity check passed!") func() except: print(SANITY_CHECK_ERR_MSG)
def showAllPLanets(self): cont = 1 planets = swapi.get_all("planets") for i in planets.order_by("name"): print(cont) print("Nome do Planeta: " + i.name) print("Diâmetro: " + i.diameter) print("Período de rotação: " + i.rotation_period) print("Período orbital: " + i.orbital_period) print("Gravidade: " + i.gravity) print("População: " + i.population) print("Clima: " + i.climate) print("Terreno: " + i.terrain) print("Superfície da água: " + i.surface_water) for j, aux in enumerate(i.residents): print("Residentes: " + i.residents[j]) for k, aux2 in enumerate(i.films): print("Quantidade de Filmes: " + i.films[k]) print("Url: " + i.url) print("Criado: " + i.created) print("Editado: " + i.edited) print("") cont = cont + 1
def film_detail(request, ide): films = swapi.get_all("films") for film in films.items: if int(ide) == film.episode_id: request.session['visited'][ film.title] = request.build_absolute_uri() return render(request, "film.html", {'f': film})
def characters(): """Renders the about page.""" #Integrate with SWAPI API characters = swapi.get_all("people") return render_template('characters.html', title='characters', characters=characters.items)
def get_starships(): try: starships = swapi.get_all("starships") except: response = {"error": "something went wrong"} return json.dumps(starships, default=lambda o: o.__dict__, indent=4)
def get_planets(self): print("Loading Planets data....") data = {} data['planets'] = [] planets = swapi.get_all("planets") for planet in planets.order_by("name"): data['planets'].append(planet.name) self.write_to_json_file('planets', data)
def exercise_one(): print(exercise_list[0]) for film in swapi.get_all("films").iter(): if film.title == "Return of the Jedi": ships = film.get_starships() for ship in ships.iter(): print(ship.name) break
def exercise_two(): print(exercise_list[1]) for ship in swapi.get_all("starships").iter(): try: if float(ship.hyperdrive_rating) >= 1.0: print(ship.name) except: pass
def get_films(self): print("Loading Movies data....") data = {} data['films'] = [] films = swapi.get_all("films") for film in films.order_by("title"): data['films'].append(film.title) self.write_to_json_file('films', data)
def getPlanetByName(self, namePlanet): planets = swapi.get_all("planets") for p in planets.order_by("name"): if (p.name == namePlanet): return p return None
def handle(self, *args, **options): # get data from api api_starships = swapi.get_all('starships').items objs = Starship.objects.bulk_create( (Starship(**self.normalize_api_starship(starship)) for starship in api_starships)) self.stdout.write(self.style.SUCCESS(f'Created {objs}'))
def q4(): species = swapi.get_all("species").iter() for sp in species: if sp.name == "Dug": target = sp break films = target.get_films().iter() return films
def q2(): people = swapi.get_all("people").iter() pilot = set() for person in people: for sh in person.get_starships().iter(): if sh: pilot.add(person) break return list(pilot)
def vehicles_speed_over(speed): vehicle = swapi.get_all('vehicles') vehicle_names = vehicle.items vn_list = [] for vn in vehicle_names: if vn.max_atmosphering_speed == 'unknown': continue if int(vn.max_atmosphering_speed) > speed: vn_list.append(vn.name) #print(vn.name) return vn_list
def film_compare(request): film_search = request.POST.get('film_search', False) if not film_search or len(film_search) < 1: return redirect('Error') films, result = swapi.get_all("films").order_by("release_date"), [] for film in films: if film_search.upper() in film.title.upper(): result.append(film) return render(request, "detail.html", { 'film_search': film_search, 'films': result })
def storePlanet(name, climate, terrain): allPlanets = swapi.get_all("planets") newPlanet = {"name": name, "climate": climate, "terrain": terrain, "films_counting": 0, "created_at": datetime.datetime.utcnow()} for planet in allPlanets.items: if planet.name == name: newPlanet['films_counting'] = len(planet.films) break return str(collection.insert_one(newPlanet).inserted_id)
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
def get_movies_list_by_ep(): movie_set = swapi.get_all("films") movies = [] for movie in movie_set.items: movies.append((movie.episode_id, movie.title)) movies.sort(key=itemgetter(0)) #print (movies) dict = {'movies': movies} return dict
def get_vehicle_speeds(): if not VEHICLE_SPEEDS: # Get vehicle name-speed mapping vehicles = swapi.get_all('vehicles') for vehicle in vehicles.iter(): try: speed = int(vehicle.max_atmosphering_speed) except Exception as err: print err speed = -1 VEHICLE_SPEEDS.append({'vehicle': vehicle.name, 'speed': speed}) return VEHICLE_SPEEDS
def get_all_swapi(): n = 1 result = [] mensagem = {'Erro':'Nenhum planeta encontrado'} #SWAPI planets = swapi.get_all("planets") for r in planets.order_by("created"): result.append({'_id':n,'nome':r.name,'clima':r.climate,'terreno':r.terrain,'quantidade de aparições em filmes: ' : len(r.films)}) n+=1 if len(result) == 0: return mensagem else: return result
def get_chars(): chars = cache.get('chars') if not chars: swapi_characters = swapi.get_all("people") chars = {} for char in swapi_characters.items: char_index = swapi_characters.items.index(char) + 1 char_name = char.name.lower() chars[char_name] = char_index char_key = get_char_cache_key(char_name, char_index) cache.set(char_key, char) cache.set('chars', chars) return chars
def get_all_swapi(): n = 1 result = [] mensagem = {'Erro': 'Nenhum planeta encontrado'} #SWAPI planets = swapi.get_all("planets") for r in planets.order_by("created"): result.append({ '_id': n, 'nome': r.name, 'clima': r.climate, 'terreno': r.terrain, 'quantidade de aparições em filmes: ': len(r.films) }) n += 1 if len(result) == 0: return mensagem else: return result
def exercise_three(): print(exercise_list[2]) for ship in swapi.get_all("starships").iter(): try: if "-" in ship.crew: min_crews, max_crews = map(int, ship.crew.split("-")) if if_crews_between_3_and_100(min_crews): print(ship.name) elif if_crews_between_3_and_100(max_crews): print(ship.name) elif "," in ship.crew: crews = int("".join(ship.crew.split(","))) if if_crews_between_3_and_100(crews): print(ship.name) else: crews = int(ship.crew) if if_crews_between_3_and_100(crews): print(ship.name) except: pass
def get_context_data(self, **kwargs): """ Get people from the api and save them to the database after truncating all data """ data = super().get_context_data(**kwargs) Person.objects.all().delete() # Person with id of 1 person_1 = swapi.get_person(1) Person.objects.create(name=person_1.name, eye_color=person_1.eye_color, height=person_1.height, birth_year=person_1.birth_year, gender='hidden') people = swapi.get_all('people') people_with_blue_eyes = [] for person in people.items: if person.eye_color == 'blue': people_with_blue_eyes.append(person) # People with blue eyes for person in people_with_blue_eyes: if person.name != person_1.name: Person.objects.create( name=person.name if person.name else 'hidden', eye_color='hidden', height=person.height if person.height else 'hidden', birth_year='hidden', gender=person.gender if person.gender else 'hidden') data.update({'people': Person.objects.all()}) return data
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
# Starship Databank in Star Wars ### SWAPI & Tkinter Modules import swapi import tkinter as tk import tkinter.font as tkf from tkinter import ttk from tkinter import messagebox ### Extract People Data ships = swapi.get_all('starships') dataset = {} for ship in ships.iter(): dataset[ship.name] =[ship.name, ship.model, ship.length, ship.cargo_capacity, ship.starship_class, ship.manufacturer, ship.max_atmosphering_speed, ship.hyperdrive_rating, ship.consumables, ship.cost_in_credits, ship.pilots, ship.crew, ship.passengers, ship.created, ship.edited, ship.films, ship.get_films, ship.get_pilots, ship.url] num = len(dataset) headers = ['name', 'model', 'length', 'cargo_capacity', 'starship_class', 'manufacturer', 'max_atmosphering_speed', 'hyperdrive_rating', 'consumables', 'cost_in_credits', 'pilots', 'crew', 'passengers', 'created', 'edited', 'films', 'get_films', 'get_pilots', 'url'] header_widths = [180, 250, 40, 40, 120, 160, 30, 30, 30, 30, 120, 30, 30, 120, 120, 120, 120, 120, 120]
# People Databank in Star Wars ### SWAPI & Tkinter Modules import swapi import tkinter as tk import tkinter.font as tkf from tkinter import ttk from tkinter import messagebox ### Extract People Data persons = swapi.get_all('people') dataset = {} for person in persons.iter(): dataset[person.name] =[person.name, person.gender, person.birth_year, person.species, person.eye_color, person.skin_color, person.hair_color, person.height, person.mass, person.homeworld, person.starships, person.vehicles, person.created, person.edited, person.films, person.get_films, person.get_homeworld, person.get_species, person.get_starships, person.get_vehicles, person.url] num = len(dataset) headers = ['name', 'gender', 'birth_year', 'species', 'eye_color', 'skin_color', 'hair_color', 'height', 'mass', 'homeworld', 'starships', 'vehicles', 'created', 'edited', 'films', 'get_films', 'get_homeworld', 'get_species', 'get_starships', 'get_vehicles', 'url'] header_widths = [120, 30, 60, 180, 60, 60, 60, 30, 60, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120]
def q3(): vehicles = swapi.get_all("vehicles").iter() mas = [vi.max_atmosphering_speed for vi in vehicles] return mas
def source_swapi_starship_raw(): """ Fetch raw starship data """ return swapi.get_all("starships")
# Planet Databank of Star Wars ### SWAPI & Tkinter Modules import swapi import tkinter as tk import tkinter.font as tkf from tkinter import ttk from tkinter import messagebox ### Extract Planet Data planets = swapi.get_all('planets') dataset = {} for planet in planets.iter(): dataset[planet.name] =[planet.name, planet.diameter, planet.gravity, planet.climate, planet.rotation_period, planet.orbital_period, planet.terrain, planet.surface_water, planet.population, planet.residents, planet.films, planet.created, planet.edited, planet.get_films, planet.get_residents, planet.url] num = len(dataset) headers = ['name', 'diameter', 'gravity', 'climate', 'rotation_period', 'orbital_period', 'terrain', 'surface_water', 'population', 'residents', 'films', 'created', 'edited', 'get_films', 'get_residents', 'url'] header_widths = [80, 30, 90, 140, 30, 30, 240, 60, 50, 120, 120, 100, 100, 100, 100, 100]
def source_swapi_film_raw(): """ Fetch raw films data """ return swapi.get_all("films")
for film in films: if film['title'] == 'Revenge of the Sith': target = film break print(f'{len(target["species"])} species in Revenge of the Sith') ''' print(f'\n[1] Number of Species Test:\n') film = get(ResourceType.FILM, 6) print(f'{len(film["species"])} species in Revenge of the Sith') print(f'\n[2] Films Episode Id Test:\n') films = get_all(ResourceType.FILM) films.sort(key=lambda elem: elem['episode_id']) for film in films: print(f'{film["title"]:28s} - episode id = {film["episode_id"]}') print(f'\n[3] Vehicles Max Atomosphering Speed Test:\n') vehicles = get_all(ResourceType.VEHICLE) for vehicle in vehicles: try: vehicle['max_atmosphering_speed'] = int( vehicle['max_atmosphering_speed']) except: vehicle['max_atmosphering_speed'] = -1 vehicles.sort(key=lambda elem: elem['max_atmosphering_speed'])
# install https://github.com/phalt/swapi-python import swapi planets = swapi.get_all('planets') records = [] for p in planets.iter(): if p.name == "unknown": continue try: diameter = int(p.diameter) except ValueError: diameter = p.diameter else: if diameter == 0: diameter = u"unknown" records.append((p.name.replace(' ', '_'), diameter, p.terrain.replace(' ', '').replace(',', '/'))) with open("planets.dat", "w") as output: for name, diameter, terrain in records: output.write("{0:15s} {1:9} {2}\n".format(name, diameter, terrain))
def q1(): planets = swapi.get_all("planets").order_by("diameter") return planets
def test_get_all(self): people = swapi.get_all('people') self.assertEquals(people.count(), 87) self.assertEquals('<PeopleQuerySet - 87>', people.__repr__())
def test_get_all(self): people = swapi.get_all('people') self.assertEquals(people.count(), 82) self.assertEquals('<PeopleQuerySet - 82>', people.__repr__())