Spaces:
Sleeping
Sleeping
import http.client | |
import pandas as pd | |
import numpy as np | |
import json | |
import os | |
def get_flight(departureId, arrivalId, departureDate): | |
conn = http.client.HTTPSConnection("booking-com15.p.rapidapi.com") | |
rapid_key = os.getenv("RAPIDAPI_KEY") | |
headers = { | |
'x-rapidapi-key': rapid_key, #Replace with your own RapidAPI key | |
'x-rapidapi-host': "booking-com15.p.rapidapi.com" | |
} | |
conn.request("GET", f"/api/v1/flights/searchFlights?fromId={departureId}.AIRPORT&toId={arrivalId}.AIRPORT&departDate={departureDate}¤cy_code=BRL", headers=headers) | |
res = conn.getresponse() | |
data = res.read() | |
json_data = json.loads(data.decode("utf-8")) | |
try: | |
# Get all flight offers with validation | |
if not json_data or 'data' not in json_data or 'flightOffers' not in json_data['data']: | |
return None | |
flight_offers = json_data['data']['flightOffers'] | |
if not flight_offers: | |
return None | |
# Initialize variables to track cheapest flight | |
cheapest_price = float('inf') | |
cheapest_flight = None | |
# Loop through each flight offer | |
for offer in flight_offers: | |
try: | |
# Validate price breakdown structure | |
if ('priceBreakdown' not in offer or | |
'total' not in offer['priceBreakdown'] or | |
'units' not in offer['priceBreakdown']['total']): | |
print('a estrutura está correta') | |
continue | |
# Get total price in units | |
price = float(offer['priceBreakdown']['total']['units']) | |
# Add nanos (decimal part) if present | |
if 'nanos' in offer['priceBreakdown']['total']: | |
price += float(offer['priceBreakdown']['total']['nanos']) / 1000000000 | |
# Update cheapest if current price is lower | |
if price < cheapest_price: | |
cheapest_price = price | |
cheapest_flight = offer | |
except (ValueError, TypeError): | |
continue | |
# Extract relevant info from cheapest flight | |
if cheapest_flight: | |
try: | |
result = { | |
'price': f"{cheapest_flight['priceBreakdown']['total'].get('currencyCode', 'USD')} {cheapest_price:.2f}", | |
'departure': { | |
'from': cheapest_flight['segments'][0]['departureAirport'].get('cityName', 'Unknown'), | |
'time': cheapest_flight['segments'][0].get('departureTime', 'Unknown') | |
}, | |
'arrival': { | |
'to': cheapest_flight['segments'][0]['arrivalAirport'].get('cityName', 'Unknown'), | |
'time': cheapest_flight['segments'][0].get('arrivalTime', 'Unknown') | |
}, | |
'airline': cheapest_flight['segments'][0]['legs'][0]['carriersData'][0].get('name', 'Unknown') | |
} | |
return result | |
except (KeyError, IndexError): | |
return None | |
return None | |
except Exception: | |
return None |