Exemple #1
0
 def __init__(self):
     f = open("API/code.txt", "r")
     code = f.read()
     self.amadeus = Client(
         client_id='JzlFRuOgo0pT42JHNoAVjOs8WKWxYvSq',
         client_secret=code
     )
Exemple #2
0
 def get_control_price(self):
     """Get control price."""
     try:
         amadeus = Client(client_id=os.environ['AMADEUS_API_KEY'],
                          client_secret=os.environ['AMADEUS_API_SECRET'],
                          hostname='production')
         body = self.populate_amadeus_request_body()
         response = amadeus.shopping.flight_offers_search.post(body)
         flight = None
         for flight_element in response.data:
             if self.itinerary['departure_time'] in json.dumps(
                     flight_element):
                 if self.itinerary['return_time'] in json.dumps(
                         flight_element):
                     flight = flight_element
                     break
         self.itinerary.update({
             'control_price':
             flight['price']['grandTotal'],
             'seats_left':
             flight['numberOfBookableSeats'],
             'dep_control_fare_basis':
             flight['travelerPricings'][0]['fareDetailsBySegment'][0]
             ['fareBasis'],
             'ret_control_fare_basis':
             flight['travelerPricings'][0]['fareDetailsBySegment'][1]
             ['fareBasis']
         })
     except (ResponseError, KeyError) as error:
         logging.error(
             f'{self.identifier} | '
             f'Amadeus API Error while scraping: {error.__class__.__name__} > {error}'
         )
         self.itinerary.update({'control_price': 'Error with Amadeus API'})
    def __init__(self, api_key, api_secret):
        super().__init__(api_key, api_secret)

        self.amadeus = Client(
            client_id=self.client_id, 
            client_secret=self.client_secret,
            log_level='debug')
Exemple #4
0
def get_client():
    CLIENT_API_KEY = "bCDPijBMX0J26qjRbjoM20PfX37PZGye"
    CLIENT_API_SECRET = "m519izNzO29PGEbl"
    amadeus_client = Client(
        client_id=CLIENT_API_KEY,
        client_secret=CLIENT_API_SECRET)
    return amadeus_client
Exemple #5
0
def nearest_airport(origin):
    amadeus = Client(client_id='UmuSC0LY9TgqaZoLDpBR2x74yN0GCahI',
                     client_secret='9SbiFzopXFTkVOBz')
    origin_address_list = []
    origin_state_list = []
    a_lats = []
    a_lons = []
    a_iata = []
    try:
        response = amadeus.reference_data.locations.airports.get(
            longitude=origin[1], latitude=origin[0])
        for i in response.data:
            data_dict = i
            origin_address_list.append(data_dict['name'])
            origin_state_list.append(data_dict['address']['stateCode'])
            a_lats.append(data_dict['geoCode']['latitude'])
            a_lons.append(data_dict['geoCode']['longitude'])
            a_iata.append(data_dict['iataCode'])

    except ResponseError as error:
        raise error
    df = pd.DataFrame({
        'address': origin_address_list,
        'latitude': a_lats,
        'longitude': a_lons,
        'iata code': a_iata,
        'state': origin_state_list
    })
    return df
Exemple #6
0
def test_hotel_offers(cl_id, cl_secret, kwargs, extras):

    amad = Client(client_id=cl_id, client_secret=cl_secret)

    try:
        response = amad.shopping.hotel_offers.get(**kwargs).data
        if (extras == "OKAY"):
            assert response[0]['type'] == 'hotel-offers'

    except ResponseError as error:

        if (extras == "Wrong id"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "Wrong secret"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "Wrong both"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "All wrong"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "Wrong city code"):
            assert isinstance(error, amadeus.client.errors.ClientError) == True
Exemple #7
0
def get_flights(origin, destination, date):
    amadeus = Client(
        client_id='Y8cT8SjAneWZM0piL2xcLArfMxBwepTq',
        client_secret='JIrGuoHOgU5TsDNv'
    )

    try:
        response = amadeus.shopping.flight_offers.get(origin='MAD', destination='LON', departureDate='2019-08-01')

        print(response.data)
        flights = []
        for i in range(len(response.data)):
            base_dir = response.data[i]['offerItems'][0]['services'][0]['segments'][0]['flightSegment']
            class_dir = response.data[i]['offerItems'][0]['services'][0]['segments'][0]['pricingDetailPerAdult']
            price_dir = response.data[i]['offerItems'][0]['price']
            # airport = amadeus.reference_data.airlines.get(airlineCodes=base_dir['carrierCode'])
            data = {
                "departure": {'airport': base_dir['departure']['iataCode'],
                              'date': base_dir['departure']['at']},
                'arrival': {'airport': base_dir['arrival']['iataCode'],
                            'date': base_dir['arrival']['at']},
                'class': class_dir['travelClass'],
                'price': int(float(price_dir['total'])) * 60,  # TODO: парсинг курса и преобразование ПО КУРСУ
                # 'company': airport.data[0]['commonName']
            }
            flights.append(data)
        return flights

    except ResponseError as error:
        print(error)
    def get_queryset(self):
        origin = self.request.query_params.get('origin')
        destination = self.request.query_params.get('destination')
        departure_date = self.request.query_params.get('departure_date')
        return_date = self.request.query_params.get('return_date')

        dept_date = datetime.strptime(str(departure_date), "%Y-%m-%d")
        ret_date = datetime.strptime(str(return_date), "%Y-%m-%d")

        objectset = Flight.objects.all()
        queryset = objectset.filter(origin=origin,
                                    destination=destination,
                                    departure_date=departure_date,
                                    return_date=return_date)
        if len(queryset) == 0:
            amadeus = Client(client_id=api_key, client_secret=api_secret)
            offers = amadeus.shopping.flight_offers.get(
                origin=origin,
                destination=destination,
                departureDate=dept_date.date(),
                returnDate=ret_date.date()).data
            for offer in offers:
                price_dict = (offer['offerItems'][0]['price'])
                total_price = float(price_dict['total']) + float(
                    price_dict['totalTaxes'])
                Flight.objects.create(origin=origin,
                                      destination=destination,
                                      departure_date=departure_date,
                                      return_date=return_date,
                                      price=total_price)
            queryset = objectset.filter(origin=origin,
                                        destination=destination,
                                        departure_date=departure_date,
                                        return_date=return_date)
        return queryset
Exemple #9
0
def getPOI(destlat, destlong):
    amadeus = Client(client_id='NOTHINGTOSEEHERE',
                     client_secret='THANKYOUTRYAGAIN')
    response = amadeus.reference_data.locations.points_of_interest.get(
        latitude=destlat, longitude=destlong)
    # print(response.data)

    return response.data
Exemple #10
0
def getSafety(destlat, destlong):
    amadeus = Client(client_id='NOTHINGTOSEEHERE',
                     client_secret='GETYOUROWNDAMNKEY')

    response = amadeus.safety.safety_rated_locations.get(latitude=destlat,
                                                         longitude=destlong)
    # print (response.data)
    return response.data
def finall_flow(df, df1, origin_address, dest_address, date):
    amadeus = Client(client_id='l752mUaecNtoAHgIk0xS8FU0PT7Gylhg',
                     client_secret='XorPUhfQAf0owoI4')
    total_costs = {}
    flight_costs = {}
    print(df)
    print(df1)
    for idx, row in df[:2].iterrows():
        a_code = row['iata code']
        for idx, row2 in df1[:2].iterrows():
            b_code = row2['iata code']

            try:
                response = amadeus.shopping.flight_offers_search.get(
                    originLocationCode=a_code,
                    destinationLocationCode=b_code,
                    departureDate=date,
                    adults=1)
                print(response.data[0]['price']['total'])
                flight_cost = response.data[0]['price']['total']
                flight_costs[(a_code, b_code)] = flight_cost

                driving_cost = row['cost'] + row2['cost']
                total = float(flight_cost) + float(driving_cost)
                total_costs[(a_code, b_code)] = total

            except ResponseError as error:
                print(error)
    cheapest_a = min(total_costs, key=total_costs.get)
    origin_airport = cheapest_a[0]
    dest_airport = cheapest_a[1]
    response_final = amadeus.shopping.flight_offers_search.get(
        originLocationCode=origin_airport,
        destinationLocationCode=dest_airport,
        departureDate=date,
        adults=1)
    car_cost1 = df[df['iata code'] == origin_airport]['cost'].iloc[0]
    flightt_cost = flight_costs[(origin_airport, dest_airport)]
    car_cost2 = df1[df1['iata code'] == dest_airport]['cost'].iloc[0]
    longo = df[df['iata code'] == origin_airport]['latitude'].iloc[0]
    lato = df[df['iata code'] == origin_airport]['longitude'].iloc[0]
    longd = df1[df1['iata code'] == dest_airport]['latitude'].iloc[0]
    latd = df1[df1['iata code'] == dest_airport]['longitude'].iloc[0]
    print("Start at", origin_address, "and drive to", origin_airport + ".",
          "The cost of this portion of the trip:", car_cost1)
    print()
    print("Take flight from", origin_airport, 'to', dest_airport + ".",
          "The cost of this portion of the trip:", flightt_cost)
    print()
    print("Drive from", dest_airport, "to", dest_address + ".",
          "The cost of this portion of the trip:", car_cost2)
    print()
    print("The total cost of the trip is:", total_costs[cheapest_a])
    return [
        origin_address, origin_airport, dest_airport, dest_address,
        response_final.data, total_costs[cheapest_a], car_cost1, flightt_cost,
        car_cost2, longo, lato, longd, latd
    ]
def get_flight(flight_info, codes):
    global context
    amadeus = Client(client_id=os.getenv("AMADEUS_API_KEY"),
                     client_secret=os.getenv("AMADEUS_SECRET"))
    iata_origin = iata_code_lookup(flight_info['origin_loc'],
                                   codes,
                                   origin_city=True)
    iata_dest = iata_code_lookup(flight_info['dest_loc'],
                                 codes,
                                 origin_city=False)
    if iata_origin is None:
        context = 'orig'
        result = f"I'm afraid there are no flights leaving {flight_info['origin_loc'].upper()} at this time. Their borders must still be closed. Please choose a different city."
    elif iata_dest is None:
        context = 'dest'
        result = f"I'm afraid there are no flights to {flight_info['dest_loc'].upper()} at this time. Their borders must still be closed. Please choose a different city."
    else:
        try:
            result = 'Here are the 5 cheapest options for you!\n'
            response = amadeus.shopping.flight_offers_search.get(
                originLocationCode=iata_origin,
                destinationLocationCode=iata_dest,
                departureDate=flight_info['depart_date'],
                returnDate=flight_info['return_date'],
                maxPrice=flight_info['budget'],
                currencyCode='CAD',
                adults=1)
            if len(response.data) < 1:
                return "I'm afraid I can't find any flights between these two locations for that time. Please provide updated information for a different trip."
            for i, offer in enumerate(response.data[:5]):
                to_dep = dparser.parse(
                    offer['itineraries'][0]['segments'][0]['departure']['at'],
                    fuzzy=True)
                to_arr = dparser.parse(
                    offer['itineraries'][0]['segments'][0]['arrival']['at'],
                    fuzzy=True)
                re_dep = dparser.parse(
                    offer['itineraries'][1]['segments'][0]['departure']['at'],
                    fuzzy=True)
                re_arr = dparser.parse(
                    offer['itineraries'][1]['segments'][0]['arrival']['at'],
                    fuzzy=True)
                result += f'''
✈️ Option {i+1}
Departure Time:        {to_dep.hour}:{to_dep.minute if to_dep.minute>9 else str(0)+str(to_dep.minute)} on {to_dep.year}-{to_dep.month}-{to_dep.day}
Arrival Time:          {to_arr.hour}:{to_arr.minute if to_arr.minute>9 else str(0)+str(to_arr.minute)} on {to_arr.year}-{to_arr.month}-{to_arr.day}
Flight Duration:       {offer['itineraries'][0]['duration'].strip('PT').lower()}
Return Departure Time: {re_dep.hour}:{re_dep.minute if re_dep.minute>9 else str(0)+str(re_dep.minute)} on {re_dep.year}-{re_dep.month}-{re_dep.day}
Return Arrival Time:   {re_arr.hour}:{re_arr.minute if re_arr.minute>9 else str(0)+str(re_arr.minute)} on {re_arr.year}-{re_arr.month}-{re_arr.day}
Flight Duration:       {offer['itineraries'][1]['duration'].strip('PT').lower()}
Total Price:           ${offer['price']['total']}
Flight Class:          {offer['travelerPricings'][0]['fareDetailsBySegment'][0]['cabin']}\n'''

            result += '\nWill any of these work for you? If so, please respond with "Option X". Otherwise, please say "Declined"'
        except ResponseError:
            result = 'It seems there was an error in your booking, would you like to try something else?'
    return result
Exemple #13
0
def get_hotel_offers(event, context):
    #format:
    #'id': 'hotel ID'
    #'checkInDate': 'checkInDate'
    #'checkOutDate': 'checkOutDate'

    amadeus = Client(client_id='jRfuscAlEGTr79S9bWUVED66wdGCErku',
                     client_secret='XCC7I0GCfVIz7jAr')

    payload = json.loads(event['body'])
    #payload = event
    id = payload['id']
    inDate = payload['checkInDate']
    outDate = payload['checkOutDate']

    offerList = []

    try:
        hotel_offers = amadeus.shopping.hotel_offers_by_hotel.get(
            hotelId=id, checkInDate=inDate, checkOutDate=outDate)
        hotelData = hotel_offers.data['hotel']
        offersData = hotel_offers.data['offers']

        hotelName = "%s in %s, %s" % (hotelData['name'],
                                      hotelData['address']['cityName'],
                                      hotelData['address']['stateCode'])
        offerList.append(hotelName)
        for element in offersData:
            hotelObj = {}

            hotelObj['price'] = "%s %s" % (element['price']['total'],
                                           element['price']['currency'])
            hotelObj['beds'] = "%s %s" % (
                element['room']['typeEstimated']['beds'],
                element['room']['typeEstimated']['bedType'])
            hotelObj['guests'] = "%s Adults" % (element['guests']['adults'])
            hotelObj['checkInDate'] = element['checkInDate']
            hotelObj['checkOutDate'] = element['checkOutDate']
            hotelObj['link'] = element['self']

            if hotelObj not in offerList:
                offerList.append(hotelObj)

    except ResponseError as error:
        print(error)
        pass

    response = {
        "statusCode": 200,
        "headers": {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': "true",
        },
        "body": json.dumps(offerList)
    }

    return response
Exemple #14
0
def find_airports(event, context):

    payload = json.loads(event['body'])
    city1 = payload['city1']
    city2 = payload['city2']

    amadeus = Client(client_id=AMADEUS_ID, client_secret=AMADEUS_SECRET)

    try:
        response = amadeus.reference_data.locations.get(keyword=city1,
                                                        subType=Location.ANY)
        data = response.data
    except ResponseError as error:
        data = error

    list_airports1 = []

    for airport in data:
        if airport['subType'] == "AIRPORT":
            ap = {"name": airport['name'], "iataCode": airport['iataCode']}

            if ap not in list_airports1:
                list_airports1.append(ap)

    try:
        response = amadeus.reference_data.locations.get(keyword=city2,
                                                        subType=Location.ANY)
        data = response.data
    except ResponseError as error:
        data = error

    list_airports2 = []

    for airport in data:
        if airport['subType'] == "AIRPORT":
            ap = {"name": airport['name'], "iataCode": airport['iataCode']}

            if ap not in list_airports2:
                list_airports2.append(ap)

    response = {
        "statusCode":
        200,
        "headers": {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': "true",
        },
        "body":
        json.dumps({
            'airports1': list_airports1,
            'airports2': list_airports2
        })
    }

    return response
Exemple #15
0
def hotelSearch(request, IATA):
    form = SearchForm(initial="")
    #Initialize Amadeus
    amadeus = Client(client_id="oXoHcPGNhQAKNcvvhFIkB9kFudwrBYTy",
                     client_secret="zs3PhgM4HNpZbCm4")
    response = amadeus.shopping.hotel_offers.get(cityCode=IATA)
    with open("log.json", "w+", encoding="utf-8") as log:
        json.dump(response.data, log, indent=2)
    result = response.data
    context = {'form': form, 'results': result}
    return render(request, "HotelApp\index.html", context)
Exemple #16
0
def get_hotels(event, context):

    #format:
    #'cityCode': 'cityCode'

    amadeus = Client(client_id='jRfuscAlEGTr79S9bWUVED66wdGCErku',
                     client_secret='XCC7I0GCfVIz7jAr')

    payload = json.loads(event['body'])
    #payload = event
    cityCode = payload['cityCode']

    hotelList = []

    try:
        # Get list of Hotels by city code
        hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode=cityCode)

        for element in hotels_by_city.data:
            hotelObj = {}

            hotel_id = element['hotel']['hotelId']
            name = element['hotel']['name']
            distance = ("%s %s" %
                        (element['hotel']['hotelDistance']['distance'],
                         element['hotel']['hotelDistance']['distanceUnit']))
            rating = element['hotel']['rating']
            price = ("%s %s" % (element['offers'][0]['price']['total'],
                                element['offers'][0]['price']['currency']))
            roomDesc = element['offers'][0]['room']['description']['text']

            hotelObj['name'] = name
            hotelObj['rating'] = rating
            hotelObj['distance'] = distance
            hotelObj['price'] = price
            hotelObj['hotel_id'] = hotel_id

            if hotelObj not in hotelList:
                hotelList.append(hotelObj)

    except ResponseError as error:
        response = {"message": "ERROR", "code": error}
        return response

    response = {
        "statusCode": 200,
        "headers": {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': "true",
        },
        "body": json.dumps(hotelList)
    }

    return response
Exemple #17
0
def CitiesSearch(request, IATA):
    form = SearchForm(initial = "")
   #Initialize Amadeus
    amadeus = Client(
        client_id = "oXoHcPGNhQAKNcvvhFIkB9kFudwrBYTy",
        client_secret = "zs3PhgM4HNpZbCm4"
    )
    response = amadeus.cities_offers.get(cityCode = IATA)
    # with open("static\json\log.json", "w+", encoding="utf-8") as log: -->> This creates log.json 
    #     json.dump(response.data, log, indent=2)
    result = response.data
    context = {'form' : form, 'results' : result}
    return render(request, "CitiesApp_index.html", context)
Exemple #18
0
    def call_amadeus(self):

        amadeus = Client(client_id=self.api_key, client_secret=self.api_secret)

        try:
            amadeus_resp = amadeus.reference_data.locations.get(
                keyword=str(self.city), subType=Location.CITY)
            if (amadeus_resp.data):
                desired_location = amadeus_resp.data[0]['iataCode']
                print("Destination: " + str(desired_location))
            else:
                print(
                    'This location could not be found by amadeus flight search'
                )
        except ResponseError as error:
            print(str(error.code))

        if (amadeus_resp.data):
            try:
                response = amadeus.shopping.flight_offers_search.get(
                    originLocationCode='LGW',
                    destinationLocationCode=str(desired_location),
                    departureDate=self.outbound_date,
                    adults=1)
                if (len(response.data) == 0):
                    print(
                        'No flights could be found for this location on this date.  Try a different location and/or date!'
                    )
                else:
                    self.data = response.data
                    for res in response.data:
                        print(
                            "Flight: Departing {departure_location} at {departure_time}.  Price: {price}"
                            .format(departure_location=str(
                                res['itineraries'][0]['segments'][0]
                                ['departure']['iataCode']),
                                    departure_time=str(
                                        res['itineraries'][0]['segments'][0]
                                        ['departure']['at']),
                                    price=str(res['price']['total'])))
                        """
                        print(res['price']['total'])
                        print(res['itineraries'][0]['segments']
                              [0]['departure']['iataCode'])
                        print(res['itineraries'][0]['segments']
                              [0]['departure']['at'])
                        """
                        # txt1 = "Flight: {f}, I'am {age}".format(fname = "John", age = 36)
            except ResponseError as error:
                print(error)
Exemple #19
0
def get_amadeus_client():
    with open(PATH_AMADEUS_CREDENTIALS) as f: keys = yaml.load(f)
    
    amadeus = Client(client_id=keys['API_Key'],client_secret=keys['API_Secret'])
    
    try:
        response = amadeus.reference_data.urls.checkin_links.get(airline='1X')
        #print(response.data)
        logging.debug("Connection established".format())
        # => [{'type': 'checkin-link', 'id': '1XEN-GBWeb', 'href': 'https://www....
    except ResponseError as error:
        #print(error)
        logging.error("{}".format(error))
    return amadeus
Exemple #20
0
def get_airline_name():
    from amadeus import Client, ResponseError
    import json
    args = request.args.to_dict()
    airlineCode = args['airlineCode']
    loc_dict = {}
    amadeus = Client(client_id='client_id', client_secret='secret')
    response = amadeus.reference_data.airlines.get(airlineCodes=airlineCode)
    res = response.data
    try:
        loc_dict['airline'] = res[0]['businessName']
    except:
        loc_dict['airline'] = 'name unavailable'
    return jsonify({'result': loc_dict})
Exemple #21
0
def get_airline_link():
    from amadeus import Client, ResponseError
    import json
    args = request.args.to_dict()
    airlineCode = args['airlineCode']
    loc_dict = {}
    amadeus = Client(client_id='client_id', client_secret='secret')
    response = amadeus.reference_data.urls.checkin_links.get(
        airlineCode=airlineCode)
    res = response.data
    try:
        loc_dict['airline_link'] = res[0]['href']
    except:
        loc_dict['airline_link'] = 'link unavailable'
    return jsonify({'result': loc_dict})
Exemple #22
0
    def __amadeus_client(self):
        # set credentials
        creds = yaml.safe_load(open('/home/matt/.amadeus/creds').read())

        # initialize client
        amadeus = Client(client_id=creds['api_key'],
                         client_secret=creds['api_secret'])

        # configure request and assign response
        response = amadeus.shopping.flight_offers.get(
            origin='ATL', destination=self.__dest, departureDate=self.__depart)

        # run returned query data through preferences filter
        data = self.__filter_data(response.data)

        return data
Exemple #23
0
def get_hotel_city(event, context):
    #format:
    #'cityName': 'cityName'

    amadeus = Client(client_id='jRfuscAlEGTr79S9bWUVED66wdGCErku',
                     client_secret='XCC7I0GCfVIz7jAr')

    payload = json.loads(event['body'])
    #payload = event
    cityName = payload['cityName']

    locationList = []

    try:
        response = amadeus.reference_data.locations.get(keyword=cityName,
                                                        subType=Location.ANY)

        for element in response.data:
            location = {}
            location['cityCode'] = element['address']['cityCode']

            if ('stateCode' in element['address']):
                location['cityName'] = ("%s, %s %s" %
                                        (element['address']['cityName'],
                                         element['address']['stateCode'],
                                         element['address']['countryCode']))
            else:
                location['cityName'] = ("%s, %s " %
                                        (element['address']['cityName'],
                                         element['address']['countryCode']))

            if location not in locationList:
                locationList.append(location)

    except ResponseError as error:
        response = {"message": "Failed"}
        return response

    response = {
        "statusCode": 200,
        "headers": {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': "true",
        },
        "body": json.dumps(locationList)
    }
    return response
Exemple #24
0
def hotel():
    from amadeus import Client, ResponseError
    import json
    args = request.args.to_dict()
    lat = str(args['lat'])
    lng = str(args['lng'])
    inn = request.args.get('check_in', default='', type=str)
    out = request.args.get('check_out', default='', type=str)
    adults = args['adults']
    children = request.args.get('children', default='0', type=str)
    rooms = args['rooms']
    ratings = request.args.get('ratings', default='', type=int)
    price_range = request.args.get('price_range', default='', type=str)
    currency = request.args.get('currency', default='EUR', type=str)
    sort = request.args.get('sort', default='', type=str)
    amadeus = Client(client_id='client_id', client_secret='secret')
    response = amadeus.shopping.hotel_offers.get(latitude=lat,
                                                 longitude=lng,
                                                 checkInDate=inn,
                                                 checkOutDate=out,
                                                 adults=adults,
                                                 chilAges=2,
                                                 roomQuantity=rooms,
                                                 ratings=ratings,
                                                 priceRange=price_range,
                                                 currency='EUR',
                                                 sort=sort)
    res = response.data
    resp_list = []
    for item in res:
        resp_dict = {}
        try:
            resp_dict['name'] = item['hotel']['name']
            resp_dict['rating'] = item['hotel']['rating']
            resp_dict['price'] = item['offers'][0]['price']['total']
            resp_dict['type'] = item['hotel']['type']
            resp_dict['address'] = item['hotel']['address']['lines']
            resp_dict['amenities'] = item['hotel']['amenities']
            resp_dict['contact'] = item['hotel']['contact']
            resp_dict['lng'] = item['hotel']['longitude']
            resp_dict['lat'] = item['hotel']['latitude']
            resp_dict['description'] = item['offers'][0]['room']['description']
            resp_list.append(resp_dict)
        except:
            print('error')
    return jsonify({'result': resp_list})
Exemple #25
0
def lambda_handler(event, context):
    lon = event['longitude']
    lat = event['latitude']
    # Initialize using parameters
    from amadeus import Client, ResponseError
    amadeus = Client(client_id='NMMFvsmmdcPE9rUtSLAfnic58AftCseF',
                     client_secret='9Vj03JodL6c8NR7z')
    # response = amadeus.shopping.hotel_offers.get(cityCode='PAR')
    response = amadeus.shopping.hotel_offers.get(longitude=lon, latitude=lat)

    # print(response.result) #=> The body parsed as JSON, if the result was parsable
    # response1 = amadeus.next(response) #=> returns a new response for the next page
    # print(json.dumps(response.result, indent = 2))
    res = response.result
    res1 = res["data"]

    names = []
    rating = []
    hotelDistance = []
    address = []
    contact = []
    prices = []

    for i in res1:
        names = names + [i["hotel"]["name"]]
        rating = rating + [i["hotel"]["rating"]]
        hotelDistance = hotelDistance + [i["hotel"]["hotelDistance"]]
        address = address + [i["hotel"]["address"]]
        contact = contact + [i["hotel"]["contact"]]
        prices = prices + [i["offers"][0]["price"]["total"]]

    res = []
    for i in range(len(names)):
        res = res + [{
            "name": names[i],
            "rating": rating[i],
            "hotelDistance": hotelDistance[i],
            "address": address[i],
            "contact": contact[i],
            "price": prices[i]
        }]

    # print(json.dumps(res, indent = 2))
    return res
Exemple #26
0
def findHotels(event, context):
    payload = json.loads(event['body'])
    city = payload['city']
    #city = 'New York'

    address = urllib.parse.urlencode({"address": city})
    url = 'https://maps.googleapis.com/maps/api/geocode/json?' + address + '&key=AIzaSyDX0Us0bZyz6wX8gSBJgeqIY9m7RJfji1k'
    r = requests.get(url)
    location = r.json()['results'][0]['geometry']['location']

    amadeus = Client(client_id=AMADEUS_ID, client_secret=AMADEUS_SECRET)

    try:
        response = amadeus.shopping.hotel_offers.get(latitude=location['lat'],
                                                     longitude=location['lng'],
                                                     radius='20',
                                                     radiusUnit='MILE')
        print(response.data)
    except ResponseError as error:
        print(error)

    hotels = []

    for hotel in response.data:
        h = {
            "name": hotel["hotel"]["name"],
            "rating": hotel["hotel"]["rating"],
            "city": hotel["hotel"]["address"]["cityName"],
            "cost": hotel["offers"][0]["price"]["total"]
        }

        hotels.append(h)

    response = {
        "statusCode": 200,
        "headers": {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': "true",
        },
        "body": json.dumps({'hotels': hotels})
    }

    return response
Exemple #27
0
def getCheapestFlight(depart, dest):
    amadeus = Client()
    try:
        '''
        Find cheapest dates from city to city.
        '''
        depart = str(depart)
        dest = str(dest)
        message = []
        # response = amadeus.shopping.flight_offers_search.get(originLocationCode='SEA', destinationLocationCode='LAX', departureDate='2021-04-10', returnDate='2021-04-18', adults=1, max=1)
        returnD = datetime.today() + timedelta(days=7)
        response = amadeus.shopping.flight_offers_search.get(
            originLocationCode=depart,
            destinationLocationCode=dest,
            departureDate=datetime.today().strftime('%Y-%m-%d'),
            returnDate=returnD.strftime('%Y-%m-%d'),
            adults=1)
        result = ""
        rangeFlight = len(response.data)
        print(response.data)
        for index in range(0, rangeFlight):
            flight = response.data[index]
            data = flight["itineraries"]
            for item in data:
                segment1 = item["segments"][0]
                result += "Airline: " + segment1["carrierCode"] + "<br/>"
                result += "From: " + segment1["departure"]["iataCode"] + "<br/>"
                result += "Departure date: " + segment1["departure"][
                    "at"] + "<br/>"
                result += "To: " + segment1["arrival"]["iataCode"] + "<br/>"
                result += "Return date: " + segment1["departure"][
                    "at"] + "<br/>"
                '''result += "Airline: " + segment["carrierCode"] + "<br/>"
                result += "From: " + segment["departure"]["iataCode"] + "<br/>"
                result += "Departure date: " + segment["departure"]["at"] + "<br/>"
                result += "To: " + segment["departure"]["iataCode"] + "<br/>"
                result += "Return date: " + segment["departure"]["at"] + "<br/>"'''
            result += "Price: " + flight["price"]["total"]
            message.append(result)
            result = ""
        return message
    except ResponseError as error:
        raise error
Exemple #28
0
def flight_api(location, departure, duration, budget):

    air_code = airport_code(location)

    amadeus = Client(client_id='gMB3jPrGJCXWN1g87IDNrMYV5rYJuD4h',
                     client_secret='cG4v5dCCAsPynuKA')

    try:
        response = amadeus.shopping.flight_destinations.get(
            origin=air_code,
            departureDate=departure,
            duration=duration,
            maxPrice=budget,
            viewBy="COUNTRY")
        result = main_func(response.result)
        return result
    except ResponseError as error:
        print("ERROR: ")
        print(error)
Exemple #29
0
def test_flight_offers(cl_id, cl_secret, origin, desti, departure, adul,
                       extras):

    amad = Client(client_id=cl_id, client_secret=cl_secret)

    try:
        response = amad.shopping.flight_offers_search.get(
            originLocationCode=origin,
            destinationLocationCode=desti,
            departureDate=departure,
            adults=adul).data
        if (extras == "OKAY"):
            assert response[0]['type'] == 'flight-offer'
            #assert response[0]['type'] == 'hotel-offers'

    except ResponseError as error:

        if (extras == "Wrong id"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "Wrong secret"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "Wrong both"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "All wrong"):
            assert isinstance(
                error, amadeus.client.errors.AuthenticationError) == True

        elif (extras == "Wrong city code"):
            assert isinstance(error, amadeus.client.errors.ClientError) == True

        elif (extras == "Wrong adults"):
            assert isinstance(error, amadeus.client.errors.ClientError) == True

        elif (extras == "Wrong date"):
            assert isinstance(error, amadeus.client.errors.ClientError) == True
Exemple #30
0
def main():

    api_key = 'Z9Fb2VEMHPrPue68nDfMhPV5Z8cj1YT3'
    api_secret = 'cRtDOOmAuRKL9RUv'

    amadeus = Client(client_id=api_key, client_secret=api_secret)

    res1 = amadeus.reference_data.locations.get(keyword='Bang',
                                                subType=Location.ANY)
    dest = res1.data[0]['iataCode']
    print(dest)

    try:
        print(test)
        print(dest)
        response = amadeus.shopping.flight_offers_search.get(
            originLocationCode='LGW',
            destinationLocationCode=str(dest),
            departureDate='2020-07-01',
            adults=1)
        print(response.data)
    except ResponseError as error:
        print(error)