-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflight_price_search.py
More file actions
67 lines (54 loc) · 2.8 KB
/
Copy pathflight_price_search.py
File metadata and controls
67 lines (54 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import smtplib
class LowestPrice:
"""
A class to represent the lowest price flight details.
"""
def __init__(self, price, from_airport, to_airport, out_date, return_date):
"""
Initializes the flight details.
:param price: Total price of the flight
:param from_airport: IATA code for the departure airport
:param to_airport: IATA code for the arrival airport
:param out_date: Date of departure
:param return_date: Date of return
"""
self.price = price
self.from_airport = from_airport
self.to_airport = to_airport
self.out_date = out_date
self.return_date = return_date
def find_cheapest_flight(data):
"""
Finds the cheapest flight from the given data.
:param data: JSON response containing flight data
:return: LowestPrice object containing details of the cheapest flight
"""
# If no flight data is available, return a 'Not Available' placeholder
if data is None or not data.get('data'):
print("No flight data available")
return LowestPrice("N/A", "N/A", "N/A", "N/A", "N/A")
# Extract data from the first flight for initial comparison
first_flight = data['data'][0]
lowest_price = float(first_flight["price"]["total"])
from_city = first_flight["itineraries"][0]["segments"][0]["departure"]["iataCode"]
to_city = first_flight["itineraries"][0]["segments"][0]["arrival"]["iataCode"]
out_date = first_flight["itineraries"][0]["segments"][0]["departure"]["at"].split("T")[0]
return_date = first_flight["itineraries"][1]["segments"][0]["departure"]["at"].split("T")[0]
# Initialize the lowest price flight object
cheapest_flight = LowestPrice(lowest_price, from_city, to_city, out_date, return_date)
# Loop through all flights to find the lowest price
for flight in data["data"]:
price = float(flight["price"]["total"])
if price < lowest_price:
# Update the lowest price and corresponding flight details
lowest_price = price
final_from_city = flight["itineraries"][0]["segments"][0]["departure"]["iataCode"]
final_to_city = flight["itineraries"][0]["segments"][0]["arrival"]["iataCode"]
out_date = flight["itineraries"][0]["segments"][0]["departure"]["at"].split("T")[0]
return_date = flight["itineraries"][1]["segments"][0]["departure"]["at"].split("T")[0]
# Create a new LowestPrice object with the updated lowest price details
cheapest_flight = LowestPrice(lowest_price, final_from_city, final_to_city, out_date, return_date)
# Print the lowest price found so far
print(f"Lowest price from {final_from_city} to {final_to_city} is £{lowest_price}")
# Return the cheapest flight found
return cheapest_flight