def query(self, dateFrom, dateTo, frm, to, persons): flights_cache_service = FlightsCache(self.key) result = flights_cache_service.get_cheapest_quotes( market='UK', currency='USD', locale='en-US', originplace=frm, destinationplace=to, outbounddate=dateFrom.strftime("%Y-%m-%d"), #inbounddate=dateTo.strftime("%Y-%m-%d"), adults=persons).parsed carriers = dict([(carr['CarrierId'], carr['Name']) for carr in result['Carriers']]) rv = dict(dateFrom=dateFrom, dateTo=dateTo, frm=frm, to=to, persons=persons, price=result['Quotes'][0]['MinPrice'], currency=result['Currencies'][0]['Code'], carrier=carriers[result['Quotes'][0]['OutboundLeg'] ['CarrierIds'][0]], timestamp=datetime.datetime.now()) print rv return rv
def skyscanner(msg,bot,update): if((msg.find("flight") == -1) and (msg.find("to fly") == -1) and (msg.find("fly to") == -1) and (msg.find("fly from") == -1) and (msg.find("go to") == -1)): update.message.reply_text("Are you asking for a flight?") else: try: index_to = msg.rfind("to ") index_from = msg.rfind("from ") msg = msg + " " # Som una mica ganduls i no volem que el find(" ") retorni -1 si es l'ultima paraula flights_cache_service = FlightsCache('ha306082955374085267757354385037') if (index_to) != -1: to = msg[index_to + 3:] to = to[:to.find(" ")] if (index_from) != -1: from_ = msg[index_from + 5:] from_ = from_[:from_.find(" ")] to = cityDecoder(to) from_ = cityDecoder(from_) result = flights_cache_service.get_cheapest_quotes( market='ES', currency='eur', locale='en-GB', originplace=from_["Places"][0]["PlaceId"], destinationplace=to["Places"][0]["PlaceId"], outbounddate='anytime', adults=1 ).parsed carrierID = result["Quotes"][0]["OutboundLeg"]["CarrierIds"][0] aeroSortida = result["Quotes"][0]["OutboundLeg"]["OriginId"] aeroArribada = result["Quotes"][0]["OutboundLeg"]["DestinationId"] departureDate = result["Quotes"][0]["OutboundLeg"]["DepartureDate"] carrierDic = {} for carrier in result["Carriers"]: carrierDic[carrier["CarrierId"]] = carrier["Name"]; placesDic = {} for place in result["Places"]: placesDic[place["PlaceId"]] = place place.pop('PlaceId', None) price, url = getLink(from_["Places"][0]["PlaceId"], to["Places"][0]["PlaceId"], departureDate[:10]) update.message.reply_text("Departure from "+placesDic[aeroSortida]["Name"]+ " Airport to "+placesDic[aeroArribada]["Name"]+" Airport, with departure date: " + departureDate[:10] + " from "+str(format(price, '.0f')) + " " +result["Currencies"][0]["Symbol"]+".\n\n You can book it from here: " + url) except Exception as e: print(e) update.message.reply_text("Some data seems wrong, have you indicated an origin and a destination?")
def test_get_cheapest_price_by_route(self): flights_cache_service = FlightsCache(self.api_key) self.result = flights_cache_service.get_cheapest_price_by_route( country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate=self.outbound, inbounddate=self.inbound) print("result: %s" % self.result)
def test_get_grid_prices_by_date(self): flights_cache_service = FlightsCache(self.api_key) self.result = flights_cache_service.get_grid_prices_by_date( country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate=self.outbound, inbounddate=self.inbound) self.assertTrue('Dates' in self.result) self.assertTrue(len(self.result['Dates']) > 0)
def test_get_grid_prices_by_date_json(self): flights_cache_service = FlightsCache(self.api_key, response_format='json') self.result = flights_cache_service.get_grid_prices_by_date( market='GB', currency='GBP', locale='en-GB', originplace='SIN', destinationplace='KUL', outbounddate=self.outbound, inbounddate=self.inbound).parsed self.assertTrue('Dates' in self.result) self.assertTrue(len(self.result['Dates']) > 0)
def test_get_grid_prices_by_date_xml(self): flights_cache_service = FlightsCache(self.api_key, response_format='xml') self.result = flights_cache_service.get_grid_prices_by_date( market='DE', currency='EUR', locale='de-DE', originplace='TXL', destinationplace='LHR', outbounddate=self.outbound, inbounddate=self.inbound).parsed self.assertIsNotNone(self.result.find('./Dates')) self.assertTrue(len(self.result.findall('./Dates/ArrayOfCellDto')) > 0)
def test_get_grid_prices_by_date_xml(self): flights_cache_service = FlightsCache(self.api_key, response_format="xml") self.result = flights_cache_service.get_grid_prices_by_date( market="DE", currency="EUR", locale="de-DE", originplace="TXL", destinationplace="LHR", outbounddate=self.outbound, inbounddate=self.inbound, ).parsed self.assertTrue(None != self.result.find("./Dates")) self.assertTrue(len(self.result.findall("./Dates/ArrayOfCellDto")) > 0)
def test_get_grid_prices_by_date_json(self): flights_cache_service = FlightsCache(self.api_key, response_format="json") self.result = flights_cache_service.get_grid_prices_by_date( market="GB", currency="GBP", locale="en-GB", originplace="SIN", destinationplace="KUL", outbounddate=self.outbound, inbounddate=self.inbound, ).parsed self.assertTrue("Dates" in self.result) self.assertTrue(len(self.result["Dates"]) > 0)
def test_get_cheapest_quotes_xml(self): flights_cache_service = FlightsCache( self.api_key, response_format='xml') self.result = flights_cache_service.get_cheapest_quotes( market='DE', currency='EUR', locale='de-DE', originplace='TXL', destinationplace='LHR', outbounddate=self.outbound, inbounddate=self.inbound).parsed self.assertTrue(self.result.find('./Quotes') is not None) self.assertTrue(len(self.result.findall('./Quotes/QuoteDto')) > 0)
def test_get_cheapest_price_by_route_xml(self): flights_cache_service = FlightsCache(self.api_key, response_format='xml') self.result = flights_cache_service.get_cheapest_price_by_route( market='DE', currency='EUR', locale='de-DE', originplace='DE', destinationplace='GB', outbounddate=self.outbound, inbounddate=self.inbound).parsed self.assertIsNotNone(self.result.find('./Routes')) self.assertTrue(len(self.result.findall('./Routes/RouteDto')) > 0)
def test_get_grid_prices_by_date_xml(self): flights_cache_service = FlightsCache(self.api_key, response_format='xml') self.result = flights_cache_service.get_grid_prices_by_date( market='DE', currency='EUR', locale='de-DE', originplace='TXL', destinationplace='LHR', outbounddate=self.outbound, inbounddate=self.inbound).parsed self.assertTrue(None != self.result.find('./Dates')) self.assertTrue(len(self.result.findall('./Dates/ArrayOfCellDto')) > 0)
def test_get_cheapest_price_by_route_xml(self): flights_cache_service = FlightsCache( self.api_key, response_format='xml') self.result = flights_cache_service.get_cheapest_price_by_route( market='DE', currency='EUR', locale='de-DE', originplace='DE', destinationplace='GB', outbounddate=self.outbound, inbounddate=self.inbound).parsed self.assertTrue(None != self.result.find('./Routes')) self.assertTrue(len(self.result.findall('./Routes/RouteDto')) > 0)
def query_handler(): # api_query = requests.post('http://partners.api.skyscanner.net/apiservices/pricing/v1.0').content flights_cache_service = FlightsCache(apikey) result = flights_cache_service.get_cheapest_quotes( market='UK', country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate='2017-05-28', inbounddate='2017-05-31', adults=1).parsed # return requests.get('http://partners.api.skyscanner.net/apiservices/pricing/v1.0/{my_id}?apiKey={apikey}').content # form_data = requests.form # print form_data['name'] # requests.form() return render_template("results.html", results=result)
def get_data(): return render_template('Fly.html') return requests.post( 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0').content flights_cache_service = FlightsCache('<apikey>') result = flights_cache_service.get_cheapest_quotes( country='UK', currency='GBP', locale='en-GB', originplace='SIN-sky', destinationplace='KUL-sky', outbounddate='2017-05-28', inbounddate='2017-05-31', adults=1).parsed return requests.get( 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0/{my_id}?apiKey={apikey}' ).content form_data = requests.form print form_data['name'] return "All OK"
https://github.com/Skyscanner/skyscanner-python-sdk https://skyscanner.readthedocs.io/en/latest/index.html :Authors: bejar :Version: :Created on: 23/01/2017 16:38 """ __author__ = 'bejar' from AgentUtil.APIKeys import SKYSCANNER_KEY from skyscanner.skyscanner import FlightsCache flights_cache_service = FlightsCache(SKYSCANNER_KEY) result = flights_cache_service.get_cheapest_quotes( market='UK', currency='EUR', locale='es-ES', originplace='BCN', destinationplace='GVA', outbounddate='2017-02-02', inbounddate='2017-02-07').parsed print(result)
def get_cached_offers(from_city, go_date, inbound_date): flights_service = FlightsCache(API_KEY) from_city_id = city_string_to_id(from_city) if not from_city_id: return None flight_resp = flights_service.get_cheapest_price_by_route( **{ 'market': 'CH', 'currency': 'EUR', 'locale': 'en-GB', # 'country': 'ES', 'originplace': from_city_id, 'destinationplace': 'anywhere', 'outbounddate': go_date, 'inbounddate': inbound_date, # 'adults': 1, # 'stops': 0 }) resp = flight_resp.json() carriers = dict([(carrier['CarrierId'], carrier) for carrier in resp['Carriers']]) places = dict([(place['PlaceId'], place) for place in resp['Places']]) quotes = resp['Quotes'] checkin_year, checkin_month, checkin_monthday = go_date.split('-') checkout_year, checkout_month, checkout_monthday = inbound_date.split('-') ##pp(resp) booking_str = """http://www.booking.com/searchresults.html?checkin_month={checkin_month}&checkin_monthday={checkin_monthday}&checkin_year={checkin_year}&checkout_month={checkout_month}&checkout_monthday={checkout_monthday}&checkout_year={checkout_year}&ss_all=0""".format( **{ 'checkin_year': checkin_year, 'checkin_month': checkin_month, 'checkin_monthday': checkin_monthday, 'checkout_year': checkout_year, 'checkout_month': checkout_month, 'checkout_monthday': checkout_monthday }) """{shortApiKey}""" cleaned = [{ 'price': quote['MinPrice'], 'go_carrier': carriers[quote['OutboundLeg']['CarrierIds'][0]]['Name'], 'go_timestamp': quote['OutboundLeg']['DepartureDate'], 'go_from': places[quote['OutboundLeg']['OriginId']]['CityName'] + ", " + places[quote['OutboundLeg']['OriginId']]['CountryName'], 'go_to': places[quote['OutboundLeg']['DestinationId']]['CityName'] + ", " + places[quote['OutboundLeg']['DestinationId']]['CountryName'], 'back_carrier': carriers[quote['InboundLeg']['CarrierIds'][0]]['Name'], 'back_timestamp': quote['InboundLeg']['DepartureDate'], 'back_from': places[quote['InboundLeg']['OriginId']]['CityName'] + ", " + places[quote['InboundLeg']['OriginId']]['CountryName'], 'back_to': places[quote['InboundLeg']['DestinationId']]['CityName'] + ", " + places[quote['InboundLeg']['DestinationId']]['CountryName'], 'link': "http://partners.api.skyscanner.net/apiservices/referral/v1.0/{country}/{currency}/{locale}/{originPlace}/{destinationPlace}/{outboundPartialDate}/{inboundPartialDate}?apiKey={shortApiKey}" .format( **{ 'country': 'CH', 'currency': 'EUR', 'locale': 'en-GB', 'originPlace': from_city_id, 'destinationPlace': places[quote['OutboundLeg']['DestinationId']] ['SkyscannerCode'], 'outboundPartialDate': go_date, 'inboundPartialDate': inbound_date, 'shortApiKey': API_KEY[:16] }), 'booking_link': booking_str + "&ss={ss}&ss_raw={ss_raw}".format( **{ 'ss': places[quote['OutboundLeg']['DestinationId']] ['CityName'], 'ss_raw': places[quote['OutboundLeg'] ['DestinationId']]['CityName'] }) } for quote in quotes if quote['OutboundLeg']['CarrierIds'] and quote['InboundLeg']['CarrierIds']] offers = sorted(cleaned, key=lambda x: x['price']) return offers
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
from util import process_quotes from ratelimit import rate_limited from datetime import datetime from skyscanner.skyscanner import FlightsCache from secret import key pricer = FlightsCache(key) def place_ids(place): if isinstance(place, str) or isinstance(place, int): return [place] place_attrs = [] for attr_name in ['CityId', 'IATACode', 'SkyscannerCode', 'PlaceId']: attr = place.get(attr_name) if isinstance(attr, str): attr = attr.replace('-sky', '') if attr: place_attrs.append(attr) return place_attrs def roundtrip_quote(outbound_quote, inbound_quote): return { 'OutboundLeg': outbound_quote['OutboundLeg'] or outbound_quote['InboundLeg'], 'InboundLeg': inbound_quote['InboundLeg'] or outbound_quote['OutboundLeg'], 'MinPrice': outbound_quote['MinPrice'] + inbound_quote['MinPrice'], 'MultiTicket': True }
import pandas as pd from pandas.io.json import json_normalize from skyscanner.skyscanner import FlightsCache import os import sys API_KEY = os.environ.get('SKYSCANNER_API_KEY', None) print 'API key used:', API_KEY[1] sys.stdout.flush() flights_cache_service = FlightsCache(API_KEY) def getQuotes(origin, destination, date): print 'get Quotes started' #print 'Start cache service' #flights_cache_service = FlightsCache(os.environ.get('SKYSCANNER_API_KEY', None)) oneWay = True print 'Result for get cheapest quote ' sys.stdout.flush() result = flights_cache_service.get_cheapest_quotes( market='US', currency='USD', locale='en-US', originplace=origin, destinationplace=destination, outbounddate=date, inbounddate='').parsed print 'getting places/quotes' sys.stdout.flush()
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
from skyscanner.skyscanner import FlightsCache import pandas as pd import collections flights_cache_service = FlightsCache('on537611765613459512552361233511') result = flights_cache_service.get_cheapest_quotes( market='UK', currency='EUR', locale='en-GB', originplace='AMS', destinationplace='BCN', outbounddate='2017-06', inbounddate='2017-07').parsed def flatten(d, parent_key='', sep='_'): # http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) dct = result['Quotes'] df = pd.DataFrame([flatten(x) for x in dct]) print(df)
#!/usr/bin/python3 import os import csv from skyscanner.skyscanner import FlightsCache SKYSCANNER_API_KEY = os.environ['SKYSCANNER_API_KEY'] flights_cache_service = FlightsCache(SKYSCANNER_API_KEY) def get_all_quotes(origin, destination): # Assumes majority of trips are 1 month or shorter # Skyscanner only goes up to 1 month in the future # So I'm just using the current month until the next result = flights_cache_service.get_cheapest_quotes( market='US', currency='USD', locale='en-US', originplace=origin, destinationplace=destination, outbounddate='2017-04', inbounddate='2017-05').parsed carriers = dict( [tuple(carrier.values()) for carrier in result['Carriers']]) places = dict([(p['PlaceId'], p['IataCode']) for p in result['Places']])