-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathadvanced_date_search_validation.py
More file actions
128 lines (107 loc) · 4.23 KB
/
Copy pathadvanced_date_search_validation.py
File metadata and controls
128 lines (107 loc) · 4.23 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3
"""Advanced date search with comprehensive validation.
This example demonstrates date search functionality with extensive validation
for round trip searches, including duration constraints and date validation.
"""
from datetime import datetime, timedelta
from fli.models import (
Airport,
DateSearchFilters,
FlightSegment,
PassengerInfo,
SeatType,
TimeRestrictions,
TripType,
)
from fli.search import SearchDates
def validate_dates(from_date: str, to_date: str, min_stay: int, max_stay: int) -> None:
"""Validate date ranges for round trip searches."""
start = datetime.strptime(from_date, "%Y-%m-%d").date()
end = datetime.strptime(to_date, "%Y-%m-%d").date()
today = datetime.now().date()
if start <= today:
raise ValueError("Start date must be in the future")
if end <= start:
raise ValueError("End date must be after start date")
if end - start > timedelta(days=180):
raise ValueError("Date range cannot exceed 180 days")
if min_stay < 1:
raise ValueError("Minimum stay must be at least 1 day")
if max_stay > 30:
raise ValueError("Maximum stay cannot exceed 30 days")
if min_stay > max_stay:
raise ValueError("Minimum stay cannot be greater than maximum stay")
print(f"✓ Date validation passed: {from_date} to {to_date}")
print(f"✓ Stay duration: {min_stay}-{max_stay} days")
def main() -> None:
"""Demonstrate advanced date search with validation."""
from_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
to_date = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d")
min_stay = 2
max_stay = 4
try:
validate_dates(from_date, to_date, min_stay, max_stay)
except ValueError as exc:
print(f"❌ Validation failed: {exc}")
return
stay_lengths = range(min_stay, max_stay + 1)
search = SearchDates()
weekend_trips: list[dict[str, str | int | float]] = []
print("\n🔍 Searching for round trip dates...")
for duration in stay_lengths:
outbound_date = from_date
return_date = (
datetime.strptime(outbound_date, "%Y-%m-%d") + timedelta(days=duration)
).strftime("%Y-%m-%d")
flight_segments = [
FlightSegment(
departure_airport=[[Airport.JFK, 0]],
arrival_airport=[[Airport.LAX, 0]],
travel_date=outbound_date,
time_restrictions=TimeRestrictions(
earliest_departure=9, # 9 AM
latest_departure=18, # 6 PM
),
),
FlightSegment(
departure_airport=[[Airport.LAX, 0]],
arrival_airport=[[Airport.JFK, 0]],
travel_date=return_date,
),
]
filters = DateSearchFilters(
trip_type=TripType.ROUND_TRIP,
passenger_info=PassengerInfo(adults=1),
flight_segments=flight_segments,
from_date=from_date,
to_date=to_date,
duration=duration,
seat_type=SeatType.ECONOMY,
)
results = search.search(filters)
if not results:
continue
for trip in results:
outbound, inbound = trip.date
if outbound.weekday() >= 5: # Saturday = 5, Sunday = 6
weekend_trips.append(
{
"outbound": outbound.strftime("%Y-%m-%d"),
"return": inbound.strftime("%Y-%m-%d"),
"stay_length": duration,
"price": trip.price,
}
)
if not weekend_trips:
print("❌ No weekend trips found in the specified range")
return
weekend_trips.sort(key=lambda trip: trip["price"])
print(f"\n✅ Found {len(weekend_trips)} weekend flight combinations:")
for index, trip in enumerate(weekend_trips[:5], 1): # Show top 5 options
print(f"\n{index}. Weekend Trip:")
print(f" Outbound: {trip['outbound']}")
print(f" Return: {trip['return']}")
print(f" Stay: {trip['stay_length']} days")
print(f" Price: ${trip['price']}")
if __name__ == "__main__":
main()