def get_live_quotes(origin, destination, outbounddate, inbounddate=None): pricer = Flights(key) suffix = '-sky' origin = origin + suffix destination = destination + suffix if not inbounddate: response = pricer.get_result(country='RU', currency='RUB', locale='en-GB', originplace=origin, destinationplace=destination, outbounddate=outbounddate, adults=1).parsed else: response = pricer.get_result(country='RU', currency='RUB', locale='en-GB', originplace=origin, destinationplace=destination, outbounddate=outbounddate, inbounddate=inbounddate, adults=1).parsed return response
def search_flights(origin, destination, outbound, inbound, passengers): flights_service = Flights(API_KEY) result = flights_service.get_result( country=MARKET, currency=CURRENCY, locale=LOCALE, originplace=origin, destinationplace=destination, outbounddate=outbound.strftime('%Y-%m-%d'), inbounddate=inbound.strftime('%Y-%m-%d'), adults=passengers) if result.status_code is 200: fs = FlightSearch.objects.create( origin=origin, destination=destination, outbound=outbound, inbound=inbound, passengers=passengers, status=result.parsed['Status'], query=result.parsed['Query'], session_key=result.parsed['SessionKey']) return format_flight_search(fs, result.parsed) else: raise SearchErrorException(result.status_code)
def test_get_additional_params(self): flights_service = Flights(self.api_key) additional_params = flights_service.get_additional_params( stops=0, country='US', currency='USD', locale='en-US', originplace='DTW-sky', destinationplace='PEK-sky', outbounddate=self.outbound, inbounddate=self.inbound) self.assertEqual(additional_params, {'stops': 0})
def buscarvuelo_live(origen, destino, fecha_ida, fecha_vuelta): flights_service = Flights(os.environ['api_skyscanner']) result = flights_service.get_result(errors='graceful', country='ES', currency='EUR', locale='es-ES', originplace=origen + '-sky', destinationplace=destino + '-sky', outbounddate=fecha_ida, inbounddate=fecha_vuelta, adults=1).parsed return result
def test_create_session(self): flights_service = Flights(self.api_key) poll_url = flights_service.create_session( country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate=self.outbound_days, inbounddate=self.inbound_days, adults=1) self.assertTrue(poll_url)
def test_create_session(self): flights_service = Flights(self.api_key) poll_url = flights_service.create_session( country="UK", currency="GBP", locale="en-GB", originplace="SIN-sky", destinationplace="KUL-sky", outbounddate=self.outbound_days, inbounddate=self.inbound_days, adults=1, ) self.assertTrue(poll_url)
def test_get_result(self): flights_service = Flights(self.api_key) self.result = flights_service.get_result( country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate=self.outbound_days, inbounddate=self.inbound_days, adults=1) # print(result) print("status: %s" % self.result['Status'])
def getLink(originplace_ ,destinationplace_, outbounddate_): flights_service = Flights('ha306082955374085267757354385037') result = flights_service.get_result( country='ES', currency='eur', locale='en-GB', originplace=originplace_, destinationplace=destinationplace_, outbounddate=outbounddate_, sorttype='price', sortorder='asc', adults=1).parsed return (result['Itineraries'][0]['PricingOptions'][0]['Price'],result['Itineraries'][0]['PricingOptions'][0]['DeeplinkUrl'])
class FlightasticSearch(object): FLIGHTS_SERVICE = Flights('prtl6749387986743898559646983194') def __init__(self, country='IL', currency='USD', locale='en-GB', originplace='TLV-sky', destinationplace='NYCA-sky', outbounddate='2017-04-07', inbounddate='2017-04-13', stops=0, adults=2): self._country = country self._currency = currency self._locale = locale self._originplace = originplace self._destinationplace = destinationplace self._outbounddate = outbounddate self._inbounddate = inbounddate self._stops = stops self._adults = adults def get_minimal_flight(self): result = self.FLIGHTS_SERVICE.get_result(country=self._country, currency=self._currency, locale=self._locale, originplace=self._originplace, destinationplace=self._destinationplace, outbounddate=self._outbounddate, inbounddate=self._inbounddate, stops=self._stops, adults=self._adults).parsed return result['Itineraries'][0]
def test_get_result_xml(self): flights_service = Flights(self.api_key, response_format='xml') self.result = flights_service.get_result( errors=GRACEFUL, country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate=self.outbound_days, inbounddate=self.inbound_days, adults=1).parsed self.assertIsNotNone(self.result) self.assertIsNotNone(self.result.find('./Itineraries')) self.assertTrue(len(self.result.findall('./Itineraries/ItineraryApiDto')) > 0)
def test_get_result_json(self): flights_service = Flights(self.api_key, response_format='json') self.result = flights_service.get_result( errors=GRACEFUL, country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate=self.outbound_days, inbounddate=self.inbound_days, adults=1).parsed self.assertTrue(None != self.result) self.assertTrue('Itineraries' in self.result) self.assertTrue(len(self.result['Itineraries']) > 0)
def test_get_result_xml(self): flights_service = Flights(self.api_key, response_format="xml") self.result = flights_service.get_result( errors=GRACEFUL, country="UK", currency="GBP", locale="en-GB", originplace="SIN-sky", destinationplace="KUL-sky", outbounddate=self.outbound_days, inbounddate=self.inbound_days, adults=1, ).parsed self.assertTrue(None != self.result) self.assertTrue(None != self.result.find("./Itineraries")) self.assertTrue(len(self.result.findall("./Itineraries/ItineraryApiDto")) > 0)
def test_get_result_xml(self): flights_service = Flights(self.api_key, response_format='xml') self.result = flights_service.get_result( errors=GRACEFUL, country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate=self.outbound_days, inbounddate=self.inbound_days, adults=1).parsed self.assertIsNotNone(self.result) self.assertIsNotNone(self.result.find('./Itineraries')) self.assertTrue( len(self.result.findall('./Itineraries/ItineraryApiDto')) > 0)
def live_flights_query(self, adventure, adults, max_price_pp, earliest_dept_time, latest_dept_time, earliest_ret_time, latest_ret_time): self.flights = Flights(self.live_key) try: result = self.flights.get_result( country=self.market, currency=self.currency, locale=self.locale, originplace=adventure.departure_iata+"-sky", destinationplace=adventure.return_iata+"-sky", outbounddate=adventure.departure_date.split('T')[0], inbounddate=adventure.return_date.split('T')[0], adults=adults, groupPricing=True, outbounddepartstarttime=earliest_dept_time, outbounddepartendtime=latest_dept_time, inbounddepartstarttime=earliest_ret_time, inbounddepartendtime=latest_ret_time ).parsed return result except Exception: print("ERROR: Exception trying to access Flights API:\n") print(str(Exception))
from skyscanner.skyscanner import Flights import os live_api_key = os.environ['SKYSCANNER_LIVE_KEY'] flights_service = Flights(live_api_key) result = flights_service.get_result(country='UK', currency='GBP', locale='en-GB', originplace='CWL-sky', destinationplace='DUB-sky', outbounddate='2017-05-19', inbounddate='2017-05-21', adults=1, groupPricing=True, outbounddepartstarttime="16:00", outbounddepartendtime="23:30", inbounddepartstarttime="10:00", inbounddepartendtime="23:30").parsed print(result)
from skyscanner.skyscanner import Flights from skytravel.Structures import * from skytravel.arrays import * import pygame from urllib.request import urlopen import io from json import loads from webbrowser import open_new_tab # DO NOT CHANGE api_key OR ENTER A VALID ONE api_key = 'uc817271155344762646981250767433' flights_service = Flights(api_key) currency = 'UAH' link_box_url = 'https://cloud.githubusercontent.com/assets/24274121/26486393/9bd4f85e-4203-11e7-8fca-b5ac24e7a60a.png' link_box_str = urlopen(link_box_url).read() link_box_file = io.BytesIO(link_box_str) link_box = pygame.image.load(link_box_file) link_box = pygame.transform.scale(link_box, (40, 34)) def main(): (originplace, destinationplace, outbounddate, inbounddate, adults, children, money) = get_flight_info() people = adults + children result = flights_service.get_result(country='UK', currency=currency, locale='uk-UA', originplace=originplace + '-sky',
# Searches through the SkyScanner API for flight data. ''' For how to get an API key: https://github.com/Skyscanner/skyscanner-python-sdk For SDK Usage: https://skyscanner.readthedocs.io/en/latest/usage.html For official Flight API: http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingList For Schemas: http://business.skyscanner.net/portal/en-GB/Documentation/CodeSchemas For IATA Codes: http://www.iata.org/publications/Pages/code-search.aspx ''' from skyscanner.skyscanner import Flights, FlightsCache import sys import json API_KEY = "" flights_service = Flights(API_KEY) flights_cache_service = FlightsCache(API_KEY) # Convert the data to JSON format for more organized view def make_json(data): in_json = json.dumps(data, indent=1) return in_json # Get cheapest price by date def price_by_date(): user_market = raw_input("Please enter your home country (E.g., US): ") user_currency = raw_input( "Please enter your desired currency (E.g., USD): ") user_locale = 'en-US'
from skyscanner.skyscanner import Flights import requests import json flights_service = Flights('un441765848862889553535266199036') result = flights_service.get_result(country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate='2017-05-28', inbounddate='2017-05-31', adults=1).parsed print(result) # response = requests.get('http://partners.api.skyscanner.net/apiservices/browsedates/v1.0/GB/GBP/en-GB/LON/JFK/2017-01/2017-01?apiKey=un441765848862889553535266199036') # print json.loads(response.text)
def get_csv(_from, _to, _datetime, _pax, _currency): import json import numpy as np import urllib.request as urllib import pandas as pd import time from skyscanner.skyscanner import Flights # live exchange rates forex = urllib.urlopen("http://api.fixer.io/latest").read().decode('utf-8') forex = json.loads(forex) pref_cur = _currency #api keys key1 = 'yu127659046789830628689581357894' key2 = 'prtl6749387986743898559646983194' key3 = 'nt715939468423055307709599462293' key4 = 'yu264122863541578255073284413510' key5 = 'yu216224472936393022503819569049' key6 = 'yu989879633228513818405823595252' #country code,currency,language params = [['UK', 'GBP', 'en-GB'], ['SG', 'SGD', 'en-SG'], ['MY', 'MYR', 'ms-MY'], ['ID', 'IDR', 'id-ID'], ['BR', 'BRL', 'pt-BR'], ['MX', 'MXN', 'es-MX'], ['US', 'USD', 'en-US']] params = params[0:2] count_key = 0 count = 0 for param in params: if count_key == 0: api_key = key1 elif count_key == 1: api_key = key2 elif count_key == 2: api_key = key3 flights_service = Flights(api_key) result = flights_service.get_result(country=param[0], currency=param[1], locale=param[2], originplace=_from + '-sky', destinationplace=_to + '-sky', outbounddate=_datetime, inbounddate='', adults=int(_pax)).parsed if result is None: break #time.sleep(2) cnames = [ 'Carriers', 'Country', 'Arrival', 'Departure', 'Duration(mins)', 'Number of stops', 'Price', 'Price (Original Currency)', 'Book' ] for x in result['Itineraries']: out_id = x['OutboundLegId'] x1 = x['PricingOptions'] for x2 in x1: price_orig = float(x2['Price']) price = x2['Price'] / forex['rates'][ param[1]] * forex['rates'][pref_cur] dl = x2['DeeplinkUrl'] #print(price) for r in result['Legs']: if r['Id'] == out_id: arrival = r['Arrival'] departure = r['Departure'] duration = r['Duration'] num_stops = len(r['Stops']) carriers = [] for i in r['FlightNumbers']: for c in result['Carriers']: if c['Id'] == i['CarrierId']: carriers.append(c['Name']) if count == 0: df = pd.DataFrame([[ carriers, param[0], arrival, departure, duration, num_stops, price, "{0}".format(price_orig), dl ]], columns=cnames) else: df1 = pd.DataFrame([[ carriers, param[0], arrival, departure, duration, num_stops, price, "{0}".format(price_orig), dl ]], columns=cnames) frames = [df, df1] df = pd.concat(frames) count = count + 1 count_key = count_key + 1 pd.options.display.max_colwidth = 1000 data = df.sort_values(by='Price') #data.to_csv('fareresultsnew.csv',index = False) """df['DeeplinkUrl'] = "<a href=\""+data['DeeplinkUrl']+"\">Click here to Book</a>""" HTML(data.to_html('./templates/Results.html', index=False))
def test_retry_on_http_errors(self): self.build_data.exc_to_raise = requests.HTTPError('err') # 2 http errors won't generate errors self.build_data.raises_for_indexes[10] = 2 self.build_data.mid_point() # if 3 http errors are generated, it will be raised new_data = self.build_data[:10] new_data.raises_for_indexes[5] = 3 self.assertRaises(errors.DownloadError, new_data.mid_point) flights_service = Flights('el966379157751618466416148364616') result = flights_service.get_result(country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate='2017-05-28', inbounddate='2017-05-31', adults=1).parsed def getAddressFromLatLng(latitude, longitude): # Did the geocoding request comes from a device with a # location sensor? Must be either true or false. sensor = 'false'
import requests import json # # url = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/GB/GBP/en-GB/iata/STN/SKG/2017-05-03/2017-05-05/1?apiKey=sr202365158971473983434381556340" # # params = "flyFrom=%s&to=%s&dateFrom=%s&dateTo=%s&partner=picky&passengers=1&curr=%s&directFlights=0&locale=GB" \ # # % (fly_from, fly_to, datetime_from, datetime_to, currency) # # data = requests.get(url + params).json()['data'] # data = requests.post(url, data={'Content-Type': 'application/x-www-form-urlencoded'}) # print data from skyscanner.skyscanner import Flights flights_service = Flights('sr202365158971473983434381556340') result = flights_service.get_result(country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate='2017-05-28', inbounddate='2017-05-31', adults=1).parsed print(result)
class FlightChecker: def __init__(self, browse_key, live_key, market, currency, locale): self.market = market self.currency = currency self.locale = locale self.flights_cache = FlightsCache(browse_key) self.live_key = live_key #Returns a list where the first item is the place Name, the second is the IATA code def get_place_details(self, places, place_id): details = list() for place in places: if place['PlaceId'] == place_id: details.append(place['Name']) details.append(place['IataCode']) return details def get_place_name_from_flights(self, places, place_id): for place in places: if place['Id'] == place_id: return place['Name'] #First in list is name, then second is image url def get_agent_details(self, agents, agent_id): details = list() for agent in agents: if agent['Id'] == agent_id: details.append(agent['Name']) details.append(agent['ImageUrl']) return details def get_leg_details(self, legs, leg_id): for leg in legs: if leg['Id'] == leg_id: return leg def get_carrier_names(self, carriers, journey): journey_carriers = list() for journey_carrier_id in journey['CarrierIds']: journey_carriers.append(self.get_carrier_name(carriers, journey_carrier_id)) return journey_carriers def get_carrier_name(self, carriers, carrier_id): for carrier in carriers: if carrier['CarrierId'] == carrier_id: return carrier['Name'] def next_weekday(self, d, weekday): days_ahead = weekday - d.weekday() if days_ahead <= 0: # Target day already happened this week days_ahead += 7 return d + datetime.timedelta(days_ahead) def append_if_doesnt_exist(self, target, source, key_name, attribute_name): found_existing = False for source_item in source[key_name]: for target_item in target[key_name]: if source_item[attribute_name] == target_item[attribute_name]: found_existing = True break if found_existing == False: target[key_name].append(source_item) found_existing = False return target def browse_cache_by_route_advenchas(self, search_params): i = 0 cache_results = {} while i < len(search_params.departure_dates): departure_date = search_params.departure_dates[i] return_date = search_params.return_dates[i] try: result = self.flights_cache.get_cheapest_price_by_route( market=self.market, currency=search_params.currency, locale=self.locale, originplace=search_params.origin, destinationplace=search_params.destination, outbounddate=departure_date.strftime('%Y-%m-%d'), inbounddate=return_date.strftime('%Y-%m-%d') ).parsed except Exception as exc: print('ERROR: Could not access browse cache by route') continue quotes = result['Quotes'] carriers = result['Carriers'] places = result['Places'] for quote in quotes: min_price = quote['MinPrice'] direct = quote['Direct'] price = quote['MinPrice'] cache_date = quote['QuoteDateTime'] dept = quote['OutboundLeg'] ret = quote['InboundLeg'] dept_date = dept['DepartureDate'] dept_place_details = self.get_place_details(places, dept['OriginId']) dept_place = dept_place_details[0] dept_iata = dept_place_details[1] dept_carriers = self.get_carrier_names(carriers, dept) ret_date = ret['DepartureDate'] ret_place_details = self.get_place_details(places, ret['OriginId']) ret_place = ret_place_details[0] ret_iata = ret_place_details[1] ret_carriers = self.get_carrier_names(carriers, ret) datetime_now = datetime.now() cache_datetime = datetime.strptime(cache_date, "%Y-%m-%dT%H:%M:%S") #check that the return location is correct and flights are direct and the cache date is less than 24 hours ago if search_params.origin == dept_iata and direct == True and (datetime_now - cache_datetime) < timedelta(2): advencha = CacheAdventure( price=price, direct=direct, dept_date=dept_date, dept_place=dept_place, dept_iata=dept_iata, dept_carriers=dept_carriers, ret_date=ret_date, ret_place=ret_place, ret_iata=ret_iata, ret_carriers=ret_carriers, cache_date=cache_date ) if ret_place in cache_results: cache_results[ret_place].append(advencha) else: cache_results[ret_place] = [advencha] i += 1 return cache_results def live_flights_query(self, adventure, adults, max_price_pp, earliest_dept_time, latest_dept_time, earliest_ret_time, latest_ret_time): self.flights = Flights(self.live_key) try: result = self.flights.get_result( country=self.market, currency=self.currency, locale=self.locale, originplace=adventure.departure_iata+"-sky", destinationplace=adventure.return_iata+"-sky", outbounddate=adventure.departure_date.split('T')[0], inbounddate=adventure.return_date.split('T')[0], adults=adults, groupPricing=True, outbounddepartstarttime=earliest_dept_time, outbounddepartendtime=latest_dept_time, inbounddepartstarttime=earliest_ret_time, inbounddepartendtime=latest_ret_time ).parsed return result except Exception: print("ERROR: Exception trying to access Flights API:\n") print(str(Exception)) def parse_live_price(self, result, adults, max_price_pp): itineraries = result['Itineraries'] legs = result['Legs'] places = result['Places'] agents = result['Agents'] cheap_itineraries = list() for itinerary in itineraries: pricing = itinerary['PricingOptions'] for price in pricing: full_price = price['Price'] if full_price <= max_price_pp: flight_agents = list() for single_agent in price['Agents']: flight_agents.append(self.get_agent_details(agents, single_agent)) if 'DeeplinkUrl' in price: link = price['DeeplinkUrl'] outbound_leg_details = self.get_leg_details(legs, itinerary['OutboundLegId']) inbound_leg_details = self.get_leg_details(legs, itinerary['InboundLegId']) dept_from = self.get_place_name_from_flights(places, outbound_leg_details['OriginStation']) dept_time = outbound_leg_details['Departure'] dept_duration = outbound_leg_details['Duration'] dept_stops = len(outbound_leg_details['Stops']) dept_arrive_location = self.get_place_name_from_flights(places, outbound_leg_details['DestinationStation']) dept_arrive_time = outbound_leg_details['Arrival'] ret_from = self.get_place_name_from_flights(places, inbound_leg_details['OriginStation']) ret_time = inbound_leg_details['Departure'] ret_duration = inbound_leg_details['Duration'] ret_stops = len(inbound_leg_details['Stops']) ret_arrive_location = self.get_place_name_from_flights(places, inbound_leg_details['DestinationStation']) ret_arrive_time = inbound_leg_details['Arrival'] flight_itinerary = FlightItinerary( price=full_price, agents=flight_agents, link=link, adults=adults, dept_from=dept_from, dept_time=dept_time, dept_duration=dept_duration, dept_stops=dept_stops, dept_arrive_location=dept_arrive_location, dept_arrive_time=dept_arrive_time, ret_from=ret_from, ret_time=ret_time, ret_duration=ret_duration, ret_stops=ret_stops, ret_arrive_location=ret_arrive_location, ret_arrive_time=ret_arrive_time ) cheap_itineraries.append(flight_itinerary) return cheap_itineraries
# see https://github.com/Skyscanner/skyscanner-python-sdk from skyscanner.skyscanner import Flights flights_service = Flights('7a3621970amsh9275d1c7c9ed661p15c96ajsnbc45c95d106c') result = flights_service.get_result(country='DE', currency='EUR', locale='de-DE', originplace='MUC-sky', destinationplace='HNL-sky', outbounddate='2020-05-28', inbounddate='2020-05-31', adults=1).parsed print(result)
def get_flights_service(): keys = get_keys() return Flights(keys[0])