Example #1
0
def query(request):
    # get params:
    budget = int(request.POST["budget"])
    origin = request.POST["origin"]
    num_passengers = int(request.POST["num_passengers"])

    # calc departure_date - 7 days from now:
    today = datetime.datetime.now()
    x_days_after = today + datetime.timedelta(days=NUM_DAYS_FROM_NOW)
    departure_date = '%s--%s' % (today.strftime(DATE_FORMAT),
                                 x_days_after.strftime(DATE_FORMAT))
    logger.debug(departure_date)
    # calc max price:
    max_price = int(budget / num_passengers)
    logger.debug(type(max_price))

    # query amadeus:
    flights = Flights(AMADEUS_API_KEY)
    resp = flights.extensive_search(origin=origin,
                                    destination='LAX',
                                    departure_date=departure_date,
                                    max_price=budget)

    # TODO: remove flights with less seats then needed - can't

    return JsonResponse(data=resp, status=200)
Example #2
0
 def getFlights(self):
     flights = Flights(AMADEUS_KEY)
     resp = flights.extensive_search(
         origin='MAD',
         destination='BCN',
         departure_date='2017-06-05--2017-06-28')
     return resp
Example #3
0
def retrieve_destinations(origin, budget_query, departure_date, duration):
    # Query for flights via Amadeus
    flights = Flights(AMADEUS_API_KEY)

    # Find flights from origin
    origin_iata = flights.auto_complete(term=origin)[0]['value']

    r = flights.inspiration_search(origin=origin_iata,
                                   departure_date=departure_date,
                                   max_price=budget_query,
                                   duration=duration)

    # Cap number of experiences
    results = r['results'][:NUM_EXPERIENCES]

    # Map IATA codes from Amadeus API to human-readable places
    destinations = []
    for iata in results:
        destination = IATA2CITY.get(iata['destination'], None)
        if destination is not None:
            # Return a tuple of HRF city, dates, and price of flight
            destinations.append((destination, origin_iata, iata['destination'],
                                 iata['departure_date'], iata['return_date'],
                                 float(iata['price'])))
    return destinations
Example #4
0
def getInspirationFlights(current, leaves, price, duration=None):
    flights = Flights(API_KEY)
    return flights.inspiration_search(origin=current,
                                      departure_date=leaves,
                                      duration=duration,
                                      max_price=price)


# pprint.pprint(getCheapestFlights(current, to, leaves))

# pprint.pprint(resp)

# import amadeus

# API_KEY = keys['amadeus']['private']

# def getCheapestFlights(from, to, leaves, returns=None):
#     flight = amadeus.Flights(API_KEY)
#     return flight.low_fare_search(
#         origin = from,
#         destination = to,
#         departure_date=leaves + "" if returns is None else "--{}".format(returns)
#     )

# departure_date = "2016-11-25"
Example #5
0
def find_flight(orig, dest, event_date, latitude, longitude):
    amideus_api = app.config['AMADEUS_KEY']
    airport_content = urlopen(
        "https://api.sandbox.amadeus.com/v1.2/airports/nearest-relevant?apikey="
        + amideus_api + "&latitude=" + latitude + "&longitude=" +
        longitude).read()
    flights = Flights(amideus_api)

    # Convert to datetime object
    event_date = datetime.datetime.strptime(event_date,
                                            '%Y-%m-%d %H:%M:%S').date()

    # Decrememnt date to get departures before the event
    depart_high = event_date - datetime.timedelta(days=1)
    depart_low = event_date - datetime.timedelta(days=3)

    # String for range of dates
    departure_string = str(depart_low) + "--" + str(depart_high)

    # The request :)
    resp = flights.extensive_search(origin=orig,
                                    destination=dest,
                                    departure_date=departure_string,
                                    duration='4--7',
                                    max_price=3000)

    # print json.dumps(resp, indent=2, sort_keys=True)
    # currency = resp['currency']

    # Loop through each found flight and print its info
    ret = []
    for flight in resp.get('results', [])[:5]:
        airline = flight['airline']
        departure_date = datetime.datetime.strptime(flight['departure_date'],
                                                    '%Y-%m-%d')
        return_date = datetime.datetime.strptime(flight['return_date'],
                                                 '%Y-%m-%d')
        price = flight['price']

        # Create a URL to find these flights on google
        url_string = "https://www.google.com/flights/#search;f=%s;t=%s;d=%s;r=%s;a=%s" % (
            orig, dest, str(departure_date.date()), str(
                return_date.date()), airline)

        ret += [
            "For %s you can fly to %s departing on %s and returning on %s" %
            (price, dest, departure_date.strftime('%b %d, %Y'),
             return_date.strftime('%b %d, %Y'))
        ]

    return ret
Example #6
0
def getFlights(request):
    flights = Flights('Zt0AY8d5B9UA7ERLccCjiGF6l6gpcUoS')
    if request.method == 'POST':
        form = FlightForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            resp = flights.extensive_search(
                origin=data['origin'],
                destination=data['destination'],
                #departure_date = '2018-05-15--2018-05-30'
                departure_date=data['startdate'])
            #print(resp)
            #return HttpResponse(resp['results'][0]['price'])
        return HttpResponse(json.dumps(resp))
Example #7
0
def find_best_travel(self,
                     list_airports=None,
                     days=None,
                     num_countries=None,
                     departure_date=None):
    flights = Flights('KwG8uSgsdnyDstlNsMeKCPioagUNLYJS')
    if departure_date == None:
        departure_date = time.time()

    days_per_city = int(days / num_countries)
    distance_matrix = np.zeros((len(list_airports), len(list_airports)))
    total = len(list_airports) * len(list_airports)
    counter = 0
    for i, airport_departure in enumerate(list_airports):
        print(airport_departure)
        for j, airport_arrival in enumerate(list_airports):
            print(airport_arrival)
            if airport_arrival == airport_departure:
                distance_matrix[i, j] = 0
            else:
                prices_list = []
                for duration in range(0, days, days_per_city):
                    print(duration)
                    date = datetime.datetime.fromtimestamp(
                        departure_date +
                        duration * 24 * 3600).strftime('%Y-%m-%d')
                    print(date)
                    resp = flights.low_fare_search(origin=airport_departure,
                                                   destination=airport_arrival,
                                                   departure_date=date,
                                                   duration='1')
                    try:
                        price = resp['results'][0]['fare']['total_price']
                    except:
                        continue

                    print(price)
                    prices_list.append(float(price))
                if prices_list == []:
                    distance_matrix[i, j] = 10e6
                else:
                    distance_matrix[i, j] = np.mean(prices_list)
            counter += 1
            current_task.update_state(
                state='PROGRESS',
                meta={'process_percent': round(float(counter / total), 2)})
    return distance_matrix.tolist()
Example #8
0
def find_best_travel(list_airports=None,
                     days=None,
                     num_countries=None,
                     departure_date=None):
    flights = Flights('rTgACcDGGTOrYi9vGotfQOM2wfHAGly8')
    if departure_date == None:
        departure_date = time.time()

    days_per_city = int(days / num_countries)
    distance_matrix = np.zeros((len(list_airports), len(list_airports)))
    for i, airport_departure in enumerate(list_airports):
        print(airport_departure)
        for j, airport_arrival in enumerate(list_airports):
            print(airport_arrival)
            if airport_arrival == airport_departure:
                distance_matrix[i, j] = 0
            else:
                prices_list = []
                for duration in range(0, 40, days_per_city):
                    print(duration)
                    date = datetime.datetime.fromtimestamp(
                        departure_date +
                        duration * 24 * 3600).strftime('%Y-%m-%d')
                    print(date)
                    resp = flights.low_fare_search(origin=airport_departure,
                                                   destination=airport_arrival,
                                                   departure_date=date,
                                                   duration='1')
                    try:
                        price = resp['results'][0]['fare']['total_price']
                    except:
                        continue

                    print(price)
                    prices_list.append(float(price))
                if prices_list == []:
                    distance_matrix[i, j] = 10e6
                else:
                    distance_matrix[i, j] = np.mean(prices_list)
    return distance_matrix
def my_form_post():
    form = FlightDataForm(request.form)
    email = form.email.data
    depart = form.depart.data.upper()
    dest = form.dest.data.upper()
    dates = form.dates.data
    key = 'uc3P6EbsIUyjwIfT9eQLyNdUp4CbWbem'
    flights = Flights(key)
    resp = flights.extensive_search(origin=depart,
                                    destination=dest,
                                    departure_date=dates)
    print(resp)
    a = resp['results'][0]['airline']
    b = resp['results'][0]['price']
    c = resp['results'][1]['airline']
    d = resp['results'][1]['price']
    e = resp['results'][2]['airline']
    f = resp['results'][2]['price']
    flight1 = f'{a} flight: {b}\n'
    flight2 = f'{c} flight: {d}\n'
    flight3 = f'{e} flight: {f}\n'
    smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
    smtp_server.ehlo()
    smtp_server.starttls()
    sendemail = '*****@*****.**'
    apppwd = 'kxgrfartdbtkdubf'
    smtp_server.login(sendemail, apppwd)
    #toaddr = '*****@*****.**' #CHANGE TO ACTUAL SENDER
    msg = "\r\n".join([
        "From: [email protected]", "To: [email protected]",
        "Subject: Your flight offers for the week",
        f"Your top 3 flights from {resp['origin']} to {resp['results'][3]['destination']}\n",
        flight1, flight2, flight3, "Thank You, and have a great day!"
    ])
    smtp_server.sendmail(sendemail, email, msg)
    return ('Congratulations! You have been subscribed to the mailing list.')
Example #10
0
def GenerateListsFromCity(ciudadElegidaUsuario, primerDiaPosibleSalida,
                          ultimoDiaPosibleSalida, duracion, currencyByUser):
    # importamos los modulos necesarios de amadeus y le pasamos la pw
    from amadeus import Flights
    flights = Flights('fdNSGaHphktgPWytHqHqBVhcQVVs4uVr')
    from amadeus import Hotels
    hotels = Hotels('fdNSGaHphktgPWytHqHqBVhcQVVs4uVr')

    #aseguramos que las fechas van con guiones
    primerDiaPosibleSalida_Corregido = primerDiaPosibleSalida.replace("/", "-")
    ultimoDiaPosibleSalida_Corregido = ultimoDiaPosibleSalida.replace("/", "-")

    #calculo fecha regreso  <- de momento no se emplea
    primerDiaPosibleSalida_datetime = datetime.datetime.strptime(
        primerDiaPosibleSalida, '%Y-%m-%d')
    primerDiaPosibleVuelta_datetime = primerDiaPosibleSalida_datetime + datetime.timedelta(
        days=duracion)
    primerDiaPosibleVuelta = (str(primerDiaPosibleVuelta_datetime)[:10])

    ultimoDiaPosibleSalida_datetime = datetime.datetime.strptime(
        ultimoDiaPosibleSalida, '%Y-%m-%d')
    ultimoDiaPosibleVuelta_datetime = ultimoDiaPosibleSalida_datetime + datetime.timedelta(
        days=duracion)
    ultimoDiaPosibleVuelta = (str(ultimoDiaPosibleVuelta_datetime)[:10])

    #Obtener codigo ciudad salida
    respCity = flights.auto_complete(term=ciudadElegidaUsuario)
    print(respCity)
    codigoCiudadSalida = respCity[0]['value']
    print("Buscando vuelos desde", codigoCiudadSalida)

    # Buscar vuelos
    flights = Flights('fdNSGaHphktgPWytHqHqBVhcQVVs4uVr')
    respVuelos = flights.inspiration_search(
        origin=codigoCiudadSalida,
        departure_date=primerDiaPosibleSalida_Corregido + "--" +
        ultimoDiaPosibleSalida_Corregido,
        duration=6,
        max_price=200)
    print(respVuelos)

    # Generar listas con resultados
    listadoDestinosNfila = []
    listadoDestinosLargo = []
    listadoDestinosCodigo = []
    listadoDestinosFechaSalida = []
    listadoDestinosFechaVuelta = []
    listadoDestinosPrecioVuelo = []
    listadoDestinosLats = []
    listadoDestinosLons = []
    listadoDestinosPais = []
    listadoDestinosPrecioHoteles = []

    #for i in range (len(respVuelos['results'])):
    #    print(RecuperarNumeroFromIataCode(respVuelos['results'][i]['destination']),respVuelos['results'][i]['destination'],respVuelos['results'][i]['price'])

    for i in range(len(respVuelos['results'])):
        print(i)
        posicionEnListas = RecuperarNumeroFromIataCode(
            respVuelos['results'][i]['destination'])
        listadoDestinosNfila.append(posicionEnListas)
        listadoDestinosLargo.append(
            listaMunicipalityAirports[posicionEnListas])
        listadoDestinosCodigo.append(respVuelos['results'][i]['destination'])
        listadoDestinosFechaSalida.append(
            respVuelos['results'][i]['departure_date'])
        listadoDestinosFechaVuelta.append(
            respVuelos['results'][i]['return_date'])
        listadoDestinosPrecioVuelo.append(respVuelos['results'][i]['price'])
        listadoDestinosLats.append(listaLatsAirports[posicionEnListas])
        listadoDestinosLons.append(listaLongsAirports[posicionEnListas])
        listadoDestinosPais.append(listaCountryAirports[posicionEnListas])

        #print("inciando busqueda hotel cerca de",listaLatsAirports[posicionEnListas],",",listaLongsAirports[posicionEnListas] )
        respHoteles = hotels.search_circle(
            check_in=respVuelos['results'][i]['departure_date'],
            check_out=respVuelos['results'][i]['return_date'],
            latitude=float(listaLatsAirports[posicionEnListas]),
            longitude=float(listaLongsAirports[posicionEnListas]),
            currency=currencyByUser,
            radius=30)  #km from coordenates=km from airport
        #print(respHoteles)
        precioMedioHoteles = 0
        numeroHotelesConsiderar = min(
            len(respHoteles['results']),
            5)  #max number of hotels to consider in mean price
        if numeroHotelesConsiderar == 0:
            precioMedioHoteles = 1000 * duracion
        else:
            for h in range(numeroHotelesConsiderar):
                precioDeCadaHotel = respHoteles['results'][h]['total_price'][
                    'amount']
                #        print(precioDeCadaHotel)
                #        print(respHoteles['results'][h]['location']['latitude'])
                #        print(respHoteles['results'][h]['location']['longitude'])
                precioMedioHoteles = precioMedioHoteles + float(
                    precioDeCadaHotel)
            precioMedioHoteles = round(
                precioMedioHoteles / numeroHotelesConsiderar, 2)
        listadoDestinosPrecioHoteles.append(precioMedioHoteles)

    return (listadoDestinosNfila, listadoDestinosLargo, listadoDestinosCodigo,
            listadoDestinosFechaSalida, listadoDestinosFechaVuelta,
            listadoDestinosPrecioVuelo, listadoDestinosLats,
            listadoDestinosLons, listadoDestinosPais,
            listadoDestinosPrecioHoteles)
Example #11
0
 def __init__(self, key):
     self.flights = Flights(key)
Example #12
0
__author__ = 'ASUS-PC'
import requests
from amadeus import Flights
from fuzzywuzzy import fuzz

flights = Flights("s9lQ77z7OKA0yGtJmjL1QmMPJr3a2y60")


class amadeusAdapter(object):
    def __init__(self, key):
        self.flights = Flights(key)

    def search(
            self, search, param
    ):  #inspiration search will be done according to user statements
        if search == "inspiration_search":
            resultsSet = []
            origins = None
            destinations = None
            if param.get("origin") != None:
                if param.get("origin") == "CMB" or param.get(
                        "origin") == "Colombo" or param.get(
                            "origin") == "Sri Lanka":
                    origins = [{
                        'label':
                        'Colombo - Bandaranayake International Air Port [CMB]',
                        'value': 'CMB'
                    }]
                else:
                    origins = self.autoComplete(param.get("origin"))
            if param.get("destination") != None:
Example #13
0
from amadeus import Flights
import csv
import time

flights = Flights('<YOUR API KEY HERE>')

with open('prices.csv', 'a+') as csvprecos:
    fieldnames = ['DataPesquisa','Origem', 'Destino', 'DataIda', 'Preco']

    writer = csv.DictWriter(csvprecos, fieldnames=fieldnames)

    writer.writeheader()

with open('viagens.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=';', quotechar='|')
    for row in csvreader:

        datapesquisa = time.strftime("%d-%m-%Y")
        origem = row[0]
        destino = row[1]
        dataida = row[2]

        result = flights.low_fare_search(
            origin=origem,
            destination=destino,
            currency='BRL',
            departure_date=dataida,
            )

        data = result
Example #14
0
:Authors: bejar
    

:Version: 

:Created on: 23/01/2017 16:24 

"""

from AgentUtil.APIKeys import AMADEUS_KEY
from amadeus import Flights


__author__ = 'bejar'


flights = Flights(AMADEUS_KEY)
# resp = flights.inspiration_search(
#     origin='BCN', destination='GVA',
#     departure_date="2017-01-25--2017-02-28")
#

resp = flights.extensive_search(
    origin='MAD',
    destination='BCN',
    departure_date='2017-02-05--2017-02-28',
    duration='4--10')

print resp

Example #15
0
def get_flight_searcher():
    api_key = get_api_key()
    return Flights(api_key)
Example #16
0
import cgi, cgitb
import bottle



'''origin = form.getvalue('origin')
destination = form.getvalue('destination')
departure_date = form.getvalue('date')'''
max_price = form.getvalue('max_price')

print ("content-type:text/html \r\n\r\n")
print ('<HTML>')
print ('<HEAD>')
print ('<TITLE>SAMPLE CGI PROGRAM</TITLE>')
print ('</HEAD>')
print ('<BODY>')


flights=Flights('as954p7KMzRYH5WN6JBAUz3Z04zkGDQH')
resp = flights.inspiration_search(origin='origin', 
destination='destination', departure_date='date', 
max_price='max_price') 
print resp

print "Hello World %s"%max_price
print ('</BODY>')
print ('</HTML'>)
   
   
   
Example #17
0
		coors.append([lats, longi])
	return coors


def getPointsNames(city):
	url = "https://api.sandbox.amadeus.com/v1.2/points-of-interest/yapq-search-text?city_name=" + city + "&apikey=" + amadeus_key
	request = json.loads(requests.get(url).content)
	pois = request['points_of_interest']
	titles = []
	for site in pois:
		names = site['title']
		titles.append(names)
	return titles
# =============================== Scripts ==========================================

flights = Flights(amadeus_key)
origin = 'BKK'
departure_date = None
price = None
duration = None
direct = None
aggregation_mode = None

# resp = flights.inspiration_search(
#     origin=origin,
#     departure_date=departure_date,
#     max_price=price,
#     duration=duration,
#     direct=direct,
#     aggregation_mode=aggregation_mode)
import requests
import ast
import collections
import json

from Creds import FKEY, BTOK, TTOK, TSID

#for flights 
from amadeus import Flights

#for texting
from twilio.rest import TwilioRestClient 

#inits
f_api = Flights(FKEY)
t_api = TwilioRestClient(TSID, TTOK)

USER_DICT = dict()

#do everything below when a request is received of when cron job excecutes:

#gets flight results 
results_json = f_api.inspiration_search(
    origin = self.starting_location, #use self.guest if class
    departure_date = self.departure_date, #format should be "2015-11-25--2015-11-30"
    max_price = self.cost,
    duration = '3--10') #format should be "1--10"

#add to dictionary 5 travel results
	#5 in case prices are not unique and they get overridden as keys
x = 0
Example #19
0
def get_flight_info(orig,
                    dest,
                    depart_date,
                    ret_date,
                    duration,
                    num_results='3'):

    duration2 = str(duration) + "--" + str(duration)

    print(duration2)

    flights = Flights("S1ukqxEJjvLGcmtKD1wSPEEp9apIcsiC")
    resp = flights.low_fare_search(
        origin=orig,  #'LGA'
        destination=dest,
        departure_date=depart_date,
        return_date=ret_date,
        duration=duration2,  #'4--7'
        number_of_results=num_results)  #'10'

    # Loop over all suggested flights
    if ('results' not in resp):
        return 0

    num_results = len(resp['results'])
    outbound_len = [None] * num_results
    outbound_departure_time = [None] * num_results
    outbound_departure_location = [None] * num_results
    outbound_arrival_time = [None] * num_results
    outbound_arrival_location = [None] * num_results
    inbound_len = [None] * num_results
    inbound_departure_time = [None] * num_results
    inbound_departure_location = [None] * num_results
    inbound_arrival_time = [None] * num_results
    inbound_arrival_location = [None] * num_results
    flight_price = [None] * num_results
    num_seats_available_inbound = [[] for i in range(num_results)]
    num_seats_available_outbound = [[] for i in range(num_results)]
    terminal_inbound = [[] for i in range(num_results)]
    terminal_outbound = [[] for i in range(num_results)]
    flight_number_inbound = [[] for i in range(num_results)]
    flight_number_outbound = [[] for i in range(num_results)]
    marketing_airline_inbound = [[] for i in range(num_results)]
    marketing_airline_outbound = [[] for i in range(num_results)]

    print(num_results)
    for i in range(num_results):
        # Outbound
        outbound_len[i] = len(
            resp['results'][i]['itineraries'][0]['outbound']['flights']) - 1

        outbound_departure_time[i] = resp['results'][i]['itineraries'][0][
            'outbound']['flights'][0]['departs_at']
        outbound_departure_location[i] = resp['results'][i]['itineraries'][0][
            'outbound']['flights'][0]['origin']['airport']

        outbound_arrival_time[i] = resp['results'][i]['itineraries'][0][
            'outbound']['flights'][outbound_len[i]]['arrives_at']
        outbound_arrival_location[i] = resp['results'][i]['itineraries'][0][
            'outbound']['flights'][outbound_len[i]]['destination']['airport']

        for j in resp['results'][i]['itineraries'][0]['outbound']['flights']:
            num_seats_available_outbound[i].append(
                j['booking_info']['seats_remaining'])
            if 'terminal' in j['destination']:
                terminal_outbound[i].append(j['destination']['terminal'])
            else:
                terminal_outbound[i].append('TBD')
            flight_number_outbound[i].append(j['flight_number'])
            marketing_airline_outbound[i].append(
                get_airline_name(j['marketing_airline']))

        # Inbound
        inbound_len[i] = len(
            resp['results'][i]['itineraries'][0]['inbound']['flights']) - 1

        inbound_departure_time[i] = resp['results'][i]['itineraries'][0][
            'inbound']['flights'][0]['departs_at']
        inbound_departure_location[i] = resp['results'][i]['itineraries'][0][
            'inbound']['flights'][0]['origin']['airport']

        inbound_arrival_time[i] = resp['results'][i]['itineraries'][0][
            'inbound']['flights'][inbound_len[i]]['arrives_at']
        inbound_arrival_location[i] = resp['results'][i]['itineraries'][0][
            'inbound']['flights'][inbound_len[i]]['destination']['airport']

        for j in resp['results'][i]['itineraries'][0]['inbound']['flights']:
            num_seats_available_inbound[i].append(
                j['booking_info']['seats_remaining'])
            if 'terminal' in j['destination']:
                terminal_inbound[i].append(j['destination']['terminal'])
            else:
                terminal_inbound[i].append('TBD')
            flight_number_inbound[i].append(j['flight_number'])
            marketing_airline_inbound[i].append(
                get_airline_name(j['marketing_airline']))

        flight_price[i] = resp['results'][i]['fare']['total_price']

    return outbound_len, inbound_len, outbound_departure_time, outbound_departure_location, outbound_arrival_time, outbound_arrival_location, inbound_departure_time, inbound_departure_location, inbound_arrival_time, inbound_arrival_location, flight_price, num_seats_available_inbound, num_seats_available_outbound, terminal_inbound, terminal_outbound, flight_number_inbound, flight_number_outbound, marketing_airline_inbound, marketing_airline_outbound
Example #20
0
#!/usr/bin/env python

from amadeus import Flights
from constants import *
import sys

if __name__ == "__main__":
    if len(API_KEY) == 0:
        raise Exception(
            "Obtain an API key from sandbox.amadeus.com and store it in constants.py"
        )
        sys.exit()

    print "Flight search:"
    flights = Flights(API_KEY)
    resp = flights.inspiration_search(origin='BKK',
                                      departure_date="2018-03-25--2018-03-30",
                                      max_price=200)
    print resp