Google Flights MCP, CLI and Python Library
Add Examples and Update Docs (#9)
Punit Arani593995d393b1
diff --git a/README.md b/README.mdindex b0aab8a..8fd1130 100644--- a/README.md+++ b/README.md@@ -196,15 +196,27 @@ The MCP server provides two main tools:```pythonfrom datetime import datetime, timedelta-from fli.models import Airport, PassengerInfo, SeatType, MaxStops, SortBy-from fli.search import SearchFlights, SearchFlightsFilters+from fli.models import (+ Airport,+ PassengerInfo,+ SeatType,+ MaxStops,+ SortBy,+ FlightSearchFilters,+ FlightSegment+)+from fli.search import SearchFlights# Create search filters-filters = SearchFlightsFilters(- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,- departure_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+filters = FlightSearchFilters(passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+ )+ ],seat_type=SeatType.ECONOMY,stops=MaxStops.NON_STOP,sort_by=SortBy.CHEAPEST,@@ -226,6 +238,61 @@ for flight in flights:print(f"π To: {leg.arrival_airport.value} at {leg.arrival_datetime}")```+### Running Examples++We provide 11 comprehensive examples in the `examples/` directory that demonstrate various use cases:++```bash+# Run examples with uv (recommended)+uv run python examples/basic_one_way_search.py+uv run python examples/round_trip_search.py+uv run python examples/date_range_search.py++# Or install dependencies first, then run directly+pip install pydantic curl_cffi httpx+python examples/basic_one_way_search.py+```++**Available Examples:**++* `basic_one_way_search.py` - Simple one-way flight search+* `round_trip_search.py` - Round-trip flight booking+* `date_range_search.py` - Find cheapest dates+* `complex_flight_search.py` - Advanced filtering and multi-passenger+* `time_restrictions_search.py` - Time-based filtering+* `date_search_with_preferences.py` - Weekend filtering+* `price_tracking.py` - Price monitoring over time+* `error_handling_with_retries.py` - Robust error handling+* `result_processing.py` - Data analysis with pandas+* `complex_round_trip_validation.py` - Advanced round-trip with validation+* `advanced_date_search_validation.py` - Complex date search with filtering++> π‘ **Tip**: Examples include automatic dependency checking and will show helpful installation instructions if dependencies are missing.++## Examples++For comprehensive examples demonstrating all features, see the [`examples/`](examples/) directory:++```bash+# Quick test - run a simple example+uv run python examples/basic_one_way_search.py++# Run all examples to explore different features+uv run python examples/round_trip_search.py+uv run python examples/complex_flight_search.py+uv run python examples/price_tracking.py+```++**Example Categories:**++* **Basic Usage**: One-way, round-trip, date searches+* **Advanced Filtering**: Time restrictions, airlines, seat classes+* **Data Analysis**: Price tracking, result processing with pandas+* **Error Handling**: Retry logic, robust error management+* **Complex Scenarios**: Multi-passenger, validation, business rules++Each example is self-contained and includes automatic dependency checking with helpful installation instructions.+## Development```bashdiff --git a/docs/api/search.md b/docs/api/search.mdindex 71a87ec..9f5e4a4 100644--- a/docs/api/search.md+++ b/docs/api/search.md@@ -12,7 +12,7 @@ The main search functionality for finding specific flights.A simplified interface for flight search parameters.-::: fli.models.google_flights.FlightSearchFilters+::: fli.models.google\_flights.FlightSearchFilters## Date Search@@ -31,14 +31,19 @@ Search functionality for finding the cheapest dates to fly.### Basic Flight Search```python-from fli.search import SearchFlights, SearchFlightsFilters-from fli.models import Airport, SeatType+from fli.search import SearchFlights+from fli.models import Airport, SeatType, FlightSearchFilters, FlightSegment, PassengerInfo# Create filters-filters = SearchFlightsFilters(- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,- departure_date="2024-06-01",+filters = FlightSearchFilters(+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date="2024-06-01",+ )+ ],seat_type=SeatType.ECONOMY)@@ -51,12 +56,18 @@ results = search.search(filters)```pythonfrom fli.search import SearchDates-from fli.models import DateSearchFilters, Airport+from fli.models import DateSearchFilters, Airport, FlightSegment, PassengerInfo# Create filtersfilters = DateSearchFilters(- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date="2024-06-01",+ )+ ],from_date="2024-06-01",to_date="2024-06-30")@@ -66,10 +77,32 @@ search = SearchDates()results = search.search(filters)```+### Running These Examples++You can find complete, runnable versions of these examples in the `examples/` directory:++```bash+# Run with uv (recommended)+uv run python examples/basic_one_way_search.py+uv run python examples/date_range_search.py++# Or install dependencies and run directly+pip install pydantic curl_cffi httpx+python examples/basic_one_way_search.py+```++For more advanced examples, see:++* `examples/complex_flight_search.py` - Advanced filtering+* `examples/result_processing.py` - Data analysis+* `examples/error_handling_with_retries.py` - Robust error handling++> π‘ All examples include automatic dependency checking and helpful error messages.+## HTTP ClientThe underlying HTTP client used for API requests.### Client-::: fli.search.client.Client\ No newline at end of file+::: fli.search.client.Clientdiff --git a/docs/examples/advanced.md b/docs/examples/advanced.mdindex 6d06c9f..430b648 100644--- a/docs/examples/advanced.md+++ b/docs/examples/advanced.md@@ -1,27 +1,49 @@# Advanced Examples+This document contains advanced code examples demonstrating complex flight search scenarios. All examples are available as runnable scripts in the `examples/` directory.++## Running Examples++```bash+# Run with uv (recommended - handles dependencies automatically)+uv run python examples/complex_flight_search.py+uv run python examples/time_restrictions_search.py+uv run python examples/price_tracking.py++# Or install dependencies first, then run directly+pip install pydantic curl_cffi httpx pandas tenacity+python examples/complex_flight_search.py+```++> π‘ **Tip**: All example files include automatic dependency checking and will show helpful installation instructions if dependencies are missing.+## Complex Flight Search### Search with Multiple Filters```pythonfrom fli.models import (- Airport, Airline, SeatType, MaxStops,- PassengerInfo, TimeRestrictions, LayoverRestrictions+ Airport, Airline, SeatType, MaxStops, TripType,+ PassengerInfo, TimeRestrictions, LayoverRestrictions,+ FlightSearchFilters, FlightSegment)-from fli.search import SearchFlights, SearchFlightsFilters+from fli.search import SearchFlights# Create detailed filters-filters = SearchFlightsFilters(+filters = FlightSearchFilters(trip_type=TripType.ONE_WAY,- departure_airport=Airport.JFK,- arrival_airport=Airport.LHR,- departure_date="2024-06-01",passenger_info=PassengerInfo(adults=2,children=1,infants_on_lap=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LHR, 0]],+ travel_date="2024-06-01",+ )+ ],seat_type=SeatType.BUSINESS,stops=MaxStops.ONE_STOP_OR_FEWER,airlines=[Airline.BA, Airline.VS], # British Airways and Virgin Atlantic@@ -39,15 +61,16 @@ results = search.search(filters)### Search with Time Restrictions```python-from fli.models import TimeRestrictions-from fli.search import SearchFlights, SearchFlightsFilters+from fli.models import (+ TimeRestrictions, Airport, TripType,+ FlightSearchFilters, FlightSegment, PassengerInfo+)+from fli.search import SearchFlights# Create filters with time restrictions-filters = SearchFlightsFilters(+filters = FlightSearchFilters(trip_type=TripType.ONE_WAY,- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,- departure_date="2024-06-01",+ passenger_info=PassengerInfo(adults=1),flight_segments=[FlightSegment(departure_airport=[[Airport.JFK, 0]],@@ -73,13 +96,23 @@ results = search.search(filters)```pythonfrom datetime import datetime, timedelta-from fli.models import DateSearchFilters, Airport, SeatType+from fli.models import (+ DateSearchFilters, Airport, SeatType, TripType,+ FlightSegment, PassengerInfo+)+from fli.search import SearchDates# Create filters for weekends onlyfilters = DateSearchFilters(trip_type=TripType.ONE_WAY,- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date="2024-06-01",+ )+ ],from_date="2024-06-01",to_date="2024-06-30",seat_type=SeatType.PREMIUM_ECONOMY@@ -91,7 +124,7 @@ results = search.search(filters)# Filter for weekends onlyweekend_results = [r for r in results- if r.date.weekday() >= 5 # Saturday = 5, Sunday = 6+ if r.date[0].weekday() >= 5 # Saturday = 5, Sunday = 6]```@@ -99,14 +132,22 @@ weekend_results = [```pythonimport time-from fli.models import DateSearchFilters, Airport+from fli.models import (+ DateSearchFilters, Airport, PassengerInfo, FlightSegment+)from fli.search import SearchDatesdef track_prices(days=7):filters = DateSearchFilters(- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date="2024-06-01",+ )+ ],from_date="2024-06-01",to_date="2024-06-07")@@ -119,7 +160,7 @@ def track_prices(days=7):# Store pricesfor result in results:- date_str = result.date.strftime("%Y-%m-%d")+ date_str = result.date[0].strftime("%Y-%m-%d")if date_str not in price_history:price_history[date_str] = []price_history[date_str].append(result.price)@@ -135,12 +176,13 @@ def track_prices(days=7):### Handling Rate Limits and Retries```python-from fli.search import SearchFlights, SearchFlightsFilters+from fli.search import SearchFlights+from fli.models import FlightSearchFiltersfrom tenacity import retry, stop_after_attempt, wait_exponential@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=60))-def search_with_retry(filters: SearchFlightsFilters):+def search_with_retry(filters: FlightSearchFilters):search = SearchFlights()try:results = search.search(filters)@@ -282,7 +324,7 @@ for flight in results:```pythonfrom fli.models import (DateSearchFilters, Airport, TripType,- FlightSegment, PassengerInfo, SeatType+ FlightSegment, PassengerInfo, SeatType, TimeRestrictions)from fli.search import SearchDatesfrom datetime import datetime, timedelta@@ -365,4 +407,5 @@ for trip in weekend_trips:print(f"Outbound: {trip['outbound']} (Weekend)")print(f"Return: {trip['return']}")print(f"Duration: {trip['duration']} days")- print(f"Total Price: ${trip['price']}")\ No newline at end of file+ print(f"Total Price: ${trip['price']}")+```diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.mdindex 3df564c..637cc16 100644--- a/docs/guides/quickstart.md+++ b/docs/guides/quickstart.md@@ -143,12 +143,18 @@ for flight in results:```pythonfrom fli.search import SearchDates-from fli.models import DateSearchFilters, Airport+from fli.models import DateSearchFilters, Airport, FlightSegment, PassengerInfo# Create filtersfilters = DateSearchFilters(- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date="2024-06-01",+ )+ ],from_date="2024-06-01",to_date="2024-06-30")@@ -162,8 +168,33 @@ for date_price in results:print(f"Date: {date_price.date}, Price: ${date_price.price}")```+### Running Complete Examples++All the above code snippets are available as complete, runnable examples in the `examples/` directory:++```bash+# Run examples with uv (recommended)+uv run python examples/basic_one_way_search.py+uv run python examples/round_trip_search.py+uv run python examples/date_range_search.py++# Or install dependencies first+pip install pydantic curl_cffi httpx+python examples/basic_one_way_search.py+```++**Available Example Files:**++* `basic_one_way_search.py` - One-way flight search example+* `round_trip_search.py` - Round-trip flight search example+* `date_range_search.py` - Date range search example+* `complex_flight_search.py` - Advanced filtering example+* `error_handling_with_retries.py` - Robust error handling example++> π‘ **Tip**: Examples include automatic dependency checking and will guide you through installation if dependencies are missing.+## Next Steps-- Check out the [API Reference](../api/models.md) for detailed documentation-- See [Advanced Examples](../examples/advanced.md) for more complex use cases-- Read about [Rate Limiting and Error Handling](../api/search.md#http-client)\ No newline at end of file+* Check out the [API Reference](../api/models.md) for detailed documentation+* See [Advanced Examples](../examples/advanced.md) for more complex use cases+* Read about [Rate Limiting and Error Handling](../api/search.md#http-client)diff --git a/docs/index.md b/docs/index.mdindex 1c1ffae..2b5b55b 100644--- a/docs/index.md+++ b/docs/index.md@@ -8,26 +8,26 @@ flights and analyze pricing data.### π Direct API Access-- No web scraping or browser automation-- Fast and reliable results-- Less prone to breaking from UI changes-- Clean, modular architecture+* No web scraping or browser automation+* Fast and reliable results+* Less prone to breaking from UI changes+* Clean, modular architecture### π Search Capabilities-- One-way and round-trip flight searches-- Flexible departure times-- Multi-airline support-- Various cabin classes-- Stop preferences-- Custom result sorting+* One-way and round-trip flight searches+* Flexible departure times+* Multi-airline support+* Various cabin classes+* Stop preferences+* Custom result sorting### π° Price Analysis-- Search across date ranges-- Find cheapest dates to fly-- Price tracking and analysis-- Flexible date options+* Search across date ranges+* Find cheapest dates to fly+* Price tracking and analysis+* Flexible date options## Quick Start@@ -45,15 +45,22 @@ pipx install flights```pythonfrom datetime import datetime, timedelta-from fli.models import Airport, PassengerInfo, SeatType, MaxStops, SortBy-from fli.search import SearchFlights, SearchFlightsFilters+from fli.models import (+ Airport, PassengerInfo, SeatType, MaxStops, SortBy,+ FlightSearchFilters, FlightSegment+)+from fli.search import SearchFlights# Create search filters-filters = SearchFlightsFilters(- departure_airport=Airport.JFK,- arrival_airport=Airport.LAX,- departure_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+filters = FlightSearchFilters(passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+ )+ ],seat_type=SeatType.ECONOMY,stops=MaxStops.NON_STOP,sort_by=SortBy.CHEAPEST,@@ -70,19 +77,42 @@ for flight in flights:print(f"βοΈ Stops: {flight.stops}")```+### Running Examples++Complete, runnable examples are available in the `examples/` directory:++```bash+# Run with uv (recommended - handles dependencies)+uv run python examples/basic_one_way_search.py++# Or install dependencies first, then run+pip install pydantic curl_cffi httpx+python examples/basic_one_way_search.py+```++**Available Examples:**++* Basic one-way and round-trip searches+* Date range analysis and cheapest date finding+* Advanced filtering with time restrictions+* Error handling and retry logic+* Data analysis with pandas integration++> π‘ All examples include automatic dependency checking and helpful error messages.+## Project StructureThe library is organized into several key modules:-- `models/`: Data models and enums- - `google_flights`: Core data models specific to Google Flights- - `airline.py`: Airline enums and data- - `airport.py`: Airport enums and data+* `models/`: Data models and enums+ * `google_flights`: Core data models specific to Google Flights+ * `airline.py`: Airline enums and data+ * `airport.py`: Airport enums and data-- `search/`: Search functionality- - `flights.py`: Flight search implementation- - `dates.py`: Date-based price search- - `client.py`: HTTP client with rate limiting+* `search/`: Search functionality+ * `flights.py`: Flight search implementation+ * `dates.py`: Date-based price search+ * `client.py`: HTTP client with rate limiting## Contributing@@ -96,4 +126,4 @@ We welcome contributions! Here's how you can help:## License-This project is licensed under the MIT License. See the LICENSE file for details.\ No newline at end of file+This project is licensed under the MIT License. See the LICENSE file for details.diff --git a/examples/README.md b/examples/README.mdnew file mode 100644index 0000000..0483c89--- /dev/null+++ b/examples/README.md@@ -0,0 +1,232 @@+# Fli Examples++This directory contains practical examples demonstrating various features of the Fli flight search library. Each example is a standalone Python script that you can run directly.++## Basic Examples++### [basic\_one\_way\_search.py](basic_one_way_search.py)++**Simple one-way flight search**++* Basic flight search between two airports+* Demonstrates core API usage+* Shows result processing and display++### [round\_trip\_search.py](round_trip_search.py)++**Round trip flight search**++* Search for outbound and return flights+* Process round trip results+* Handle flight combinations++### [date\_range\_search.py](date_range_search.py)++**Search across date ranges**++* Find cheapest dates to fly+* Date-based price comparison+* Flexible departure dates++## Advanced Examples++### [complex\_flight\_search.py](complex_flight_search.py)++**Multi-filter flight search**++* Multiple passengers (adults, children, infants)+* Airline preferences+* Layover restrictions+* Duration limits+* Business class search++### [time\_restrictions\_search.py](time_restrictions_search.py)++**Time-constrained searches**++* Departure time preferences+* Arrival time constraints+* Morning vs evening flights++### [date\_search\_with\_preferences.py](date_search_with_preferences.py)++**Advanced date filtering**++* Weekend-only flights+* Day-of-week filtering+* Custom date preferences++### [complex\_round\_trip\_validation.py](complex_round_trip_validation.py)++**Enterprise-level round trip search**++* Comprehensive date validation+* Complex passenger configurations+* Multi-airline preferences+* Layover optimization+* Time restrictions for both directions++### [advanced\_date\_search\_validation.py](advanced_date_search_validation.py)++**Validated date range searching**++* Date range validation+* Stay duration constraints+* Weekend trip optimization+* Round trip date searches++## Utility Examples++### [price\_tracking.py](price_tracking.py)++**Monitor price changes**++* Track prices over time+* Price history analysis+* Trend identification+* Deal alerting concepts++### [error\_handling\_with\_retries.py](error_handling_with_retries.py)++**Robust error handling**++* Retry logic implementation+* Rate limit handling+* Exponential backoff (with tenacity)+* Fallback strategies++### [result\_processing.py](result_processing.py)++**Advanced result analysis**++* Data format conversion+* Statistical analysis+* Pandas integration (optional)+* CSV export capabilities++## Running the Examples++### Prerequisites++```bash+# Install the main library+pip install flights++# For advanced examples with optional dependencies+pip install pandas tenacity+```++### Running Examples++**Recommended approach (using uv):**++```bash+# Run any example with uv (automatically handles dependencies)+uv run python examples/basic_one_way_search.py++# Or from the project root+uv run python -m examples.basic_one_way_search+```++**Alternative approaches:**++```bash+# Option 1: Install the package first+pip install flights+python examples/basic_one_way_search.py++# Option 2: Install dependencies manually+pip install pydantic curl_cffi httpx+python examples/basic_one_way_search.py++# Option 3: Use virtual environment+python -m venv venv+source venv/bin/activate # On Windows: venv\Scripts\activate+pip install pydantic curl_cffi httpx+python examples/basic_one_way_search.py+```++**Dependency checking:**+All examples now include automatic dependency checking. If you're missing required packages, you'll see a helpful error message with installation instructions.++### Customizing Examples++Each example includes:++* Clear documentation and comments+* Configurable parameters (airports, dates, etc.)+* Error handling+* Result formatting++Feel free to modify the examples for your specific use cases:++1. **Change airports**: Replace `Airport.JFK` and `Airport.LAX` with your preferred airports+2. **Adjust dates**: Update travel dates to your desired timeframe+3. **Modify filters**: Change passenger counts, seat types, airlines, etc.+4. **Customize output**: Modify the result processing to match your needs++## Example Categories++| Category | Examples | Key Features |+|----------|----------|--------------|+| **Basic** | `basic_one_way_search`, `round_trip_search`, `date_range_search` | Core functionality, simple usage |+| **Advanced** | `complex_flight_search`, `time_restrictions_search`, `date_search_with_preferences` | Multiple filters, constraints |+| **Enterprise** | `complex_round_trip_validation`, `advanced_date_search_validation` | Validation, complex requirements |+| **Utilities** | `price_tracking`, `error_handling_with_retries`, `result_processing` | Robust implementation, analysis |++## Common Patterns++### Airport Selection++```python+from fli.models import Airport++# Major US airports+Airport.JFK, Airport.LAX, Airport.ORD, Airport.DFW+Airport.SFO, Airport.BOS, Airport.MIA, Airport.SEA++# International airports+Airport.LHR, Airport.CDG, Airport.NRT, Airport.SYD+```++### Date Handling++```python+from datetime import datetime, timedelta++# Future dates (required)+future_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")++# Date ranges+from_date = "2024-06-01"+to_date = "2024-06-30"+```++### Passenger Configuration++```python+from fli.models import PassengerInfo++# Single traveler+PassengerInfo(adults=1)++# Family with children+PassengerInfo(adults=2, children=2, infants_on_lap=1)+```++## Support++For questions about the examples or the Fli library:++* Check the [main documentation](../docs/)+* Review the [API reference](../docs/api/)+* See [advanced usage patterns](../docs/examples/advanced.md)++## Contributing++Found an issue or want to add an example? Contributions are welcome!++* Ensure examples are well-documented+* Include error handling+* Test with various configurations+* Follow the existing code stylediff --git a/examples/advanced_date_search_validation.py b/examples/advanced_date_search_validation.pynew file mode 100644index 0000000..620bd9e--- /dev/null+++ b/examples/advanced_date_search_validation.py@@ -0,0 +1,120 @@+#!/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):+ """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():+ """Demonstrate advanced date search with validation."""+ # Create flight segments for date search+ travel_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")++ segments = [+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=travel_date,+ time_restrictions=TimeRestrictions(+ earliest_departure=9, # 9 AM+ latest_departure=18, # 6 PM+ ),+ )+ ]++ # Validate and create filters+ 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 e:+ print(f"β Validation failed: {e}")+ return++ filters = DateSearchFilters(+ trip_type=TripType.ONE_WAY,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=segments,+ from_date=from_date,+ to_date=to_date,+ min_stay_days=min_stay,+ max_stay_days=max_stay,+ seat_type=SeatType.ECONOMY,+ )++ print("\nπ Searching for round trip dates...")+ search = SearchDates()+ results = search.search(filters)++ if not results:+ print("β No dates found matching criteria")+ return++ # Process results with weekend filtering+ weekend_trips = []+ for trip in results:+ travel_date = trip.date[0] # Get the travel date from the date tuple++ # Check if travel date is on weekend (5 = Saturday, 6 = Sunday)+ if travel_date.weekday() >= 5:+ weekend_trips.append(+ {+ "date": travel_date.strftime("%Y-%m-%d"),+ "day": travel_date.strftime("%A"),+ "price": trip.price,+ }+ )++ # Sort by price+ weekend_trips.sort(key=lambda x: x["price"])++ # Display results+ print(f"\nβ Found {len(weekend_trips)} weekend flights:")+ for i, trip in enumerate(weekend_trips[:5], 1): # Show top 5+ print(f"\n{i}. Weekend Flight:")+ print(f" Date: {trip['date']} ({trip['day']})")+ print(f" Price: ${trip['price']}")+++if __name__ == "__main__":+ main()diff --git a/examples/basic_one_way_search.py b/examples/basic_one_way_search.pynew file mode 100644index 0000000..afeccbf--- /dev/null+++ b/examples/basic_one_way_search.py@@ -0,0 +1,55 @@+#!/usr/bin/env python3+"""Basic one-way flight search example.++This example demonstrates how to search for one-way flights between two airports+on a specific date using the most basic configuration.+"""++from datetime import datetime, timedelta++from fli.models import (+ Airport,+ FlightSearchFilters,+ FlightSegment,+ MaxStops,+ PassengerInfo,+ SeatType,+ SortBy,+)+from fli.search import SearchFlights+++def main():+ # Create search filters+ filters = FlightSearchFilters(+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+ )+ ],+ seat_type=SeatType.ECONOMY,+ stops=MaxStops.NON_STOP,+ sort_by=SortBy.CHEAPEST,+ )++ # Search flights+ search = SearchFlights()+ flights = search.search(filters)++ # Process results+ for flight in flights:+ print(f"π° Price: ${flight.price}")+ print(f"β±οΈ Duration: {flight.duration} minutes")+ print(f"βοΈ Stops: {flight.stops}")++ for leg in flight.legs:+ print(f"\nπ« Flight: {leg.airline.value} {leg.flight_number}")+ print(f"π From: {leg.departure_airport.value} at {leg.departure_datetime}")+ print(f"π To: {leg.arrival_airport.value} at {leg.arrival_datetime}")+++if __name__ == "__main__":+ main()diff --git a/examples/complex_flight_search.py b/examples/complex_flight_search.pynew file mode 100644index 0000000..d352b08--- /dev/null+++ b/examples/complex_flight_search.py@@ -0,0 +1,64 @@+#!/usr/bin/env python3+"""Complex flight search with multiple filters.++This example demonstrates how to search for flights with detailed filters+including airlines, duration limits, and layover restrictions.+"""++from fli.models import (+ Airline,+ Airport,+ FlightSearchFilters,+ FlightSegment,+ LayoverRestrictions,+ MaxStops,+ PassengerInfo,+ SeatType,+ TripType,+)+from fli.search import SearchFlights+++def main():+ from datetime import datetime, timedelta++ # Create detailed filters+ filters = FlightSearchFilters(+ trip_type=TripType.ONE_WAY,+ passenger_info=PassengerInfo(adults=2, children=1, infants_on_lap=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LHR, 0]],+ travel_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+ )+ ],+ seat_type=SeatType.BUSINESS,+ stops=MaxStops.ONE_STOP_OR_FEWER,+ airlines=[Airline.BA, Airline.VS], # British Airways and Virgin Atlantic+ max_duration=720, # 12 hours in minutes+ layover_restrictions=LayoverRestrictions(+ airports=[Airport.BOS, Airport.ORD], # Prefer these layover airports+ max_duration=180, # Maximum 3-hour layover+ ),+ )++ search = SearchFlights()+ results = search.search(filters)++ print(f"Found {len(results)} flights:")+ for i, flight in enumerate(results, 1):+ print(f"\n--- Flight {i} ---")+ print(f"Price: ${flight.price}")+ print(f"Duration: {flight.duration} minutes")+ print(f"Stops: {flight.stops}")++ for j, leg in enumerate(flight.legs, 1):+ print(f"\nLeg {j}: {leg.airline.value} {leg.flight_number}")+ print(f" From: {leg.departure_airport.value} at {leg.departure_datetime}")+ print(f" To: {leg.arrival_airport.value} at {leg.arrival_datetime}")+ print(f" Duration: {leg.duration} minutes")+++if __name__ == "__main__":+ main()diff --git a/examples/complex_round_trip_validation.py b/examples/complex_round_trip_validation.pynew file mode 100644index 0000000..d48e3e4--- /dev/null+++ b/examples/complex_round_trip_validation.py@@ -0,0 +1,130 @@+#!/usr/bin/env python3+"""Complex round trip search with extensive validation.++This example demonstrates advanced round trip flight searching with+comprehensive validation, multiple passengers, and complex requirements.+"""++from datetime import datetime, timedelta++from fli.models import (+ Airline,+ Airport,+ FlightSearchFilters,+ FlightSegment,+ LayoverRestrictions,+ MaxStops,+ PassengerInfo,+ SeatType,+ TimeRestrictions,+ TripType,+)+from fli.search import SearchFlights+++def validate_trip_dates(outbound_date_str: str, return_date_str: str):+ """Validate trip dates with comprehensive checks."""+ today = datetime.now().date()+ outbound_date = datetime.strptime(outbound_date_str, "%Y-%m-%d").date()+ return_date = datetime.strptime(return_date_str, "%Y-%m-%d").date()++ if outbound_date <= today:+ raise ValueError("Outbound date must be in the future")+ if return_date <= outbound_date:+ raise ValueError("Return date must be after outbound date")+ if return_date - outbound_date > timedelta(days=30):+ raise ValueError("Trip duration cannot exceed 30 days")++ print(f"β Dates validated: {outbound_date} to {return_date}")+ return outbound_date, return_date+++def main():+ """Demonstrate complex round trip search with validation."""+ # Create flight segments with time restrictions+ outbound_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")++ outbound = FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LHR, 0]],+ travel_date=outbound_date,+ time_restrictions=TimeRestrictions(+ earliest_departure=6, # 6 AM+ latest_departure=12, # 12 PM+ earliest_arrival=18, # 6 PM+ latest_arrival=23, # 11 PM+ ),+ )++ return_date = (datetime.now() + timedelta(days=37)).strftime("%Y-%m-%d")++ return_flight = FlightSegment(+ departure_airport=[[Airport.LHR, 0]],+ arrival_airport=[[Airport.JFK, 0]],+ travel_date=return_date,+ time_restrictions=TimeRestrictions(+ earliest_departure=14, # 2 PM+ latest_departure=20, # 8 PM+ earliest_arrival=17, # 5 PM+ latest_arrival=23, # 11 PM+ ),+ )++ # Validate dates+ try:+ validate_trip_dates(outbound.travel_date, return_flight.travel_date)+ except ValueError as e:+ print(f"β Validation error: {e}")+ return++ # Create filters with complex requirements+ filters = FlightSearchFilters(+ trip_type=TripType.ROUND_TRIP,+ passenger_info=PassengerInfo(adults=2, children=1, infants_on_lap=1),+ flight_segments=[outbound, return_flight],+ stops=MaxStops.ONE_STOP_OR_FEWER,+ seat_type=SeatType.BUSINESS,+ airlines=[Airline.BA, Airline.VS], # British Airways and Virgin Atlantic+ max_duration=720, # 12 hours max flight time+ layover_restrictions=LayoverRestrictions(+ airports=[Airport.DUB, Airport.AMS], # Preferred layover airports+ max_duration=180, # Maximum 3-hour layover+ ),+ )++ print("\nπ Searching for complex round trip flights...")+ search = SearchFlights()+ results = search.search(filters)++ if not results:+ print("β No flights found matching criteria")+ return++ # Process results with detailed information+ print(f"\nβ Found {len(results)} flight combinations:")++ for i, (outbound, return_flight) in enumerate(results[:3], 1): # Show first 3 results+ print(f"\n{'=' * 50}")+ print(f"Option {i}: Total Price: ${outbound.price + return_flight.price}")++ print("\nπ« Outbound Flight:")+ for leg in outbound.legs:+ print(f" Flight: {leg.airline.value} {leg.flight_number}")+ print(f" From: {leg.departure_airport.value} at {leg.departure_datetime}")+ print(f" To: {leg.arrival_airport.value} at {leg.arrival_datetime}")+ print(f" Duration: {leg.duration} minutes")+ if hasattr(leg, "layover_duration") and leg.layover_duration:+ print(f" Layover: {leg.layover_duration} minutes")++ print("\nπ¬ Return Flight:")+ for leg in return_flight.legs:+ print(f" Flight: {leg.airline.value} {leg.flight_number}")+ print(f" From: {leg.departure_airport.value} at {leg.departure_datetime}")+ print(f" To: {leg.arrival_airport.value} at {leg.arrival_datetime}")+ print(f" Duration: {leg.duration} minutes")+ if hasattr(leg, "layover_duration") and leg.layover_duration:+ print(f" Layover: {leg.layover_duration} minutes")+++if __name__ == "__main__":+ main()diff --git a/examples/date_range_search.py b/examples/date_range_search.pynew file mode 100644index 0000000..22f1c52--- /dev/null+++ b/examples/date_range_search.py@@ -0,0 +1,45 @@+#!/usr/bin/env python3+"""Date range search example.++This example demonstrates how to search for the cheapest flights+across a range of dates.+"""++from fli.models import Airport, DateSearchFilters, FlightSegment, PassengerInfo+from fli.search import SearchDates+++def main():+ from datetime import datetime, timedelta++ # Create future dates+ base_date = datetime.now() + timedelta(days=30)+ travel_date = base_date.strftime("%Y-%m-%d")+ from_date = base_date.strftime("%Y-%m-%d")+ to_date = (base_date + timedelta(days=30)).strftime("%Y-%m-%d")++ # Create filters+ filters = DateSearchFilters(+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=travel_date,+ )+ ],+ from_date=from_date,+ to_date=to_date,+ )++ # Search dates+ search = SearchDates()+ results = search.search(filters)++ # Process results+ for date_price in results:+ print(f"Date: {date_price.date}, Price: ${date_price.price}")+++if __name__ == "__main__":+ main()diff --git a/examples/date_search_with_preferences.py b/examples/date_search_with_preferences.pynew file mode 100644index 0000000..4a4ea8a--- /dev/null+++ b/examples/date_search_with_preferences.py@@ -0,0 +1,61 @@+#!/usr/bin/env python3+"""Advanced date search with day preferences.++This example demonstrates how to search for flights across a date range+and filter results for specific days of the week (e.g., weekends only).+"""++from datetime import datetime, timedelta++from fli.models import (+ Airport,+ DateSearchFilters,+ FlightSegment,+ PassengerInfo,+ SeatType,+ TripType,+)+from fli.search import SearchDates+++def main():+ # Create filters for weekends only+ base_date = datetime.now() + timedelta(days=30)+ travel_date = base_date.strftime("%Y-%m-%d")+ from_date = base_date.strftime("%Y-%m-%d")+ to_date = (base_date + timedelta(days=30)).strftime("%Y-%m-%d")++ filters = DateSearchFilters(+ trip_type=TripType.ONE_WAY,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=travel_date,+ )+ ],+ from_date=from_date,+ to_date=to_date,+ seat_type=SeatType.PREMIUM_ECONOMY,+ )++ search = SearchDates()+ results = search.search(filters)++ # Filter for weekends only+ weekend_results = [+ r+ for r in results+ if r.date[0].weekday() >= 5 # Saturday = 5, Sunday = 6+ ]++ print(f"Found {len(weekend_results)} weekend flights:")+ for result in weekend_results:+ day_name = result.date[0].strftime("%A")+ date_str = result.date[0].strftime("%Y-%m-%d")+ print(f"{day_name}, {date_str}: ${result.price}")+++if __name__ == "__main__":+ main()diff --git a/examples/error_handling_with_retries.py b/examples/error_handling_with_retries.pynew file mode 100644index 0000000..1f57377--- /dev/null+++ b/examples/error_handling_with_retries.py@@ -0,0 +1,97 @@+#!/usr/bin/env python3+"""Error handling and retry logic example.++This example demonstrates how to handle rate limits and implement+retry logic for robust flight searching.+"""++from datetime import datetime, timedelta++from fli.models import Airport, FlightSearchFilters, FlightSegment, PassengerInfo+from fli.search import SearchFlights++# Note: Install tenacity with: pip install tenacity+try:+ from tenacity import retry, stop_after_attempt, wait_exponential++ TENACITY_AVAILABLE = True+except ImportError:+ TENACITY_AVAILABLE = False+ print("Warning: tenacity not installed. Install with: pip install tenacity")+++def simple_retry_search(filters: FlightSearchFilters, max_attempts=3):+ """Simple retry logic without external dependencies."""+ search = SearchFlights()++ for attempt in range(max_attempts):+ try:+ print(f"Attempt {attempt + 1}/{max_attempts}")+ results = search.search(filters)+ if not results:+ raise ValueError("No results found")+ return results+ except Exception as e:+ print(f"Search failed: {str(e)}")+ if attempt == max_attempts - 1: # Last attempt+ raise+ print("Retrying...")++ return None+++if TENACITY_AVAILABLE:++ @retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=60))+ def search_with_retry(filters: FlightSearchFilters):+ """Advanced retry logic with exponential backoff."""+ search = SearchFlights()+ try:+ results = search.search(filters)+ if not results:+ raise ValueError("No results found")+ return results+ except Exception as e:+ print(f"Search failed: {str(e)}")+ raise # Retry will handle this+++def main():+ """Demonstrate error handling approaches."""+ # Create search filters+ filters = FlightSearchFilters(+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+ )+ ],+ )++ print("=== Simple Retry Example ===")+ try:+ results = simple_retry_search(filters)+ print(f"Success! Found {len(results)} flights")+ for i, flight in enumerate(results[:3], 1): # Show first 3 results+ print(f" Flight {i}: ${flight.price}")+ except Exception as e:+ print(f"All retry attempts failed: {e}")++ if TENACITY_AVAILABLE:+ print("\n=== Advanced Retry with Tenacity ===")+ try:+ results = search_with_retry(filters)+ print(f"Success! Found {len(results)} flights")+ for i, flight in enumerate(results[:3], 1): # Show first 3 results+ print(f" Flight {i}: ${flight.price}")+ except Exception as e:+ print(f"All retry attempts failed: {e}")+ else:+ print("\n=== Advanced Retry (Tenacity not available) ===")+ print("Install tenacity to use advanced retry features: pip install tenacity")+++if __name__ == "__main__":+ main()diff --git a/examples/price_tracking.py b/examples/price_tracking.pynew file mode 100644index 0000000..2f0e9a9--- /dev/null+++ b/examples/price_tracking.py@@ -0,0 +1,72 @@+#!/usr/bin/env python3+"""Price tracking over time example.++This example demonstrates how to track flight prices over multiple days+to analyze price trends and find the best deals.+"""++import time++from fli.models import Airport, DateSearchFilters, FlightSegment, PassengerInfo+from fli.search import SearchDates+++def track_prices(days=7):+ """Track flight prices over a specified number of days."""+ from datetime import datetime, timedelta++ base_date = datetime.now() + timedelta(days=30)+ travel_date = base_date.strftime("%Y-%m-%d")+ from_date = base_date.strftime("%Y-%m-%d")+ to_date = (base_date + timedelta(days=7)).strftime("%Y-%m-%d")++ filters = DateSearchFilters(+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=travel_date,+ )+ ],+ from_date=from_date,+ to_date=to_date,+ )++ search = SearchDates()+ price_history = {}++ for day in range(days):+ print(f"Day {day + 1}: Searching for prices...")+ results = search.search(filters)++ # Store prices+ for result in results:+ date_str = result.date[0].strftime("%Y-%m-%d")+ if date_str not in price_history:+ price_history[date_str] = []+ price_history[date_str].append(result.price)++ # Wait for next check (in a real implementation, you'd wait 24 hours)+ if day < days - 1: # Don't wait on the last iteration+ print("Waiting for next check...")+ time.sleep(1) # In real usage: time.sleep(86400) for 24 hours++ return price_history+++def main():+ """Main function to demonstrate price tracking."""+ print("Starting price tracking demo...")+ price_history = track_prices(3) # Track for 3 iterations as demo++ print("\n=== Price History Summary ===")+ for date, prices in price_history.items():+ min_price = min(prices)+ max_price = max(prices)+ avg_price = sum(prices) / len(prices)+ print(f"{date}: Min: ${min_price:.2f}, Max: ${max_price:.2f}, Avg: ${avg_price:.2f}")+++if __name__ == "__main__":+ main()diff --git a/examples/result_processing.py b/examples/result_processing.pynew file mode 100644index 0000000..852d114--- /dev/null+++ b/examples/result_processing.py@@ -0,0 +1,143 @@+#!/usr/bin/env python3+"""Custom result processing and analysis example.++This example demonstrates how to process flight search results+and convert them to different formats for analysis.+"""++from datetime import datetime, timedelta++from fli.models import (+ Airport,+ FlightResult,+ FlightSearchFilters,+ FlightSegment,+ PassengerInfo,+)+from fli.search import SearchFlights++# Note: Install pandas with: pip install pandas+try:+ import pandas as pd++ PANDAS_AVAILABLE = True+except ImportError:+ PANDAS_AVAILABLE = False+ print("Warning: pandas not installed. Install with: pip install pandas")+++def analyze_results(results: list[FlightResult]) -> dict:+ """Convert results to dictionary format for analysis."""+ flights_data = []++ for flight in results:+ for leg in flight.legs:+ flights_data.append(+ {+ "price": flight.price,+ "total_duration": flight.duration,+ "stops": flight.stops,+ "airline": leg.airline.value,+ "flight_number": leg.flight_number,+ "departure_airport": leg.departure_airport.value,+ "arrival_airport": leg.arrival_airport.value,+ "departure_time": leg.departure_datetime,+ "arrival_time": leg.arrival_datetime,+ "leg_duration": leg.duration,+ }+ )++ return flights_data+++def analyze_results_pandas(results: list[FlightResult]):+ """Convert results to pandas DataFrame for advanced analysis."""+ if not PANDAS_AVAILABLE:+ print("Pandas not available. Install with: pip install pandas")+ return None++ flights_data = analyze_results(results)+ df = pd.DataFrame(flights_data)++ print("=== Flight Analysis with Pandas ===")+ print(f"Total flights analyzed: {len(df)}")+ print("\nPrice statistics:")+ print(df["price"].describe())++ print("\nAirlines distribution:")+ print(df["airline"].value_counts())++ print("\nAverage duration by airline:")+ print(df.groupby("airline")["total_duration"].mean().sort_values())++ return df+++def analyze_results_basic(results: list[FlightResult]):+ """Basic analysis without external dependencies."""+ print("=== Basic Flight Analysis ===")+ print(f"Total flights: {len(results)}")++ # Price analysis+ prices = [flight.price for flight in results]+ if prices:+ print(f"Price range: ${min(prices):.2f} - ${max(prices):.2f}")+ print(f"Average price: ${sum(prices) / len(prices):.2f}")++ # Airline analysis+ airlines = {}+ for flight in results:+ for leg in flight.legs:+ airline = leg.airline.value+ airlines[airline] = airlines.get(airline, 0) + 1++ print("\nAirlines found:")+ for airline, count in sorted(airlines.items(), key=lambda x: x[1], reverse=True):+ print(f" {airline}: {count} flights")++ # Duration analysis+ durations = [flight.duration for flight in results]+ if durations:+ print(f"\nDuration range: {min(durations)} - {max(durations)} minutes")+ print(f"Average duration: {sum(durations) / len(durations):.1f} minutes")+++def main():+ """Demonstrate result processing capabilities."""+ # Create search filters+ filters = FlightSearchFilters(+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+ )+ ],+ )++ # Search for flights+ search = SearchFlights()+ results = search.search(filters)++ if not results:+ print("No flights found for analysis")+ return++ # Basic analysis+ analyze_results_basic(results)++ # Advanced analysis with pandas (if available)+ if PANDAS_AVAILABLE:+ print("\n" + "=" * 50)+ df = analyze_results_pandas(results)++ # Save to CSV for further analysis+ if df is not None:+ filename = f"flight_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"+ df.to_csv(filename, index=False)+ print(f"\nData saved to {filename}")+++if __name__ == "__main__":+ main()diff --git a/examples/round_trip_search.py b/examples/round_trip_search.pynew file mode 100644index 0000000..36e87d3--- /dev/null+++ b/examples/round_trip_search.py@@ -0,0 +1,67 @@+#!/usr/bin/env python3+"""Round trip flight search example.++This example demonstrates how to search for round trip flights with+outbound and return segments.+"""++from fli.models import (+ Airport,+ FlightSearchFilters,+ FlightSegment,+ PassengerInfo,+ TripType,+)+from fli.search import SearchFlights+++def main():+ # Create flight segments for round trip+ from datetime import datetime, timedelta++ outbound_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")+ return_date = (datetime.now() + timedelta(days=37)).strftime("%Y-%m-%d")++ flight_segments = [+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=outbound_date,+ ),+ FlightSegment(+ departure_airport=[[Airport.LAX, 0]],+ arrival_airport=[[Airport.JFK, 0]],+ travel_date=return_date,+ ),+ ]++ # Create filters+ filters = FlightSearchFilters(+ trip_type=TripType.ROUND_TRIP,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=flight_segments,+ )++ # Search flights+ search = SearchFlights()+ results = search.search(filters)++ # Process results+ for outbound, return_flight in results:+ print("\nOutbound Flight:")+ for leg in outbound.legs:+ print(f"Flight: {leg.airline.value} {leg.flight_number}")+ print(f"Departure: {leg.departure_datetime}")+ print(f"Arrival: {leg.arrival_datetime}")++ print("\nReturn Flight:")+ for leg in return_flight.legs:+ print(f"Flight: {leg.airline.value} {leg.flight_number}")+ print(f"Departure: {leg.departure_datetime}")+ print(f"Arrival: {leg.arrival_datetime}")++ print(f"\nTotal Price: ${outbound.price + return_flight.price}")+++if __name__ == "__main__":+ main()diff --git a/examples/time_restrictions_search.py b/examples/time_restrictions_search.pynew file mode 100644index 0000000..588370a--- /dev/null+++ b/examples/time_restrictions_search.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+"""Flight search with time restrictions.++This example demonstrates how to search for flights with specific+departure and arrival time preferences.+"""++from fli.models import (+ Airport,+ FlightSearchFilters,+ FlightSegment,+ PassengerInfo,+ TimeRestrictions,+ TripType,+)+from fli.search import SearchFlights+++def main():+ from datetime import datetime, timedelta++ # Create filters with time restrictions+ filters = FlightSearchFilters(+ trip_type=TripType.ONE_WAY,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LAX, 0]],+ travel_date=(datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),+ time_restrictions=TimeRestrictions(+ earliest_departure=6, # 6 AM+ latest_departure=10, # 10 AM+ earliest_arrival=12, # 12 PM+ latest_arrival=18, # 6 PM+ ),+ )+ ],+ )++ search = SearchFlights()+ results = search.search(filters)++ print(f"Found {len(results)} flights with time restrictions:")+ for i, flight in enumerate(results, 1):+ print(f"\n--- Flight {i} ---")+ print(f"Price: ${flight.price}")+ print(f"Duration: {flight.duration} minutes")++ for leg in flight.legs:+ departure_time = leg.departure_datetime.strftime("%H:%M")+ arrival_time = leg.arrival_datetime.strftime("%H:%M")+ print(f"Flight: {leg.airline.value} {leg.flight_number}")+ print(f" Departure: {departure_time} from {leg.departure_airport.value}")+ print(f" Arrival: {arrival_time} at {leg.arrival_airport.value}")+++if __name__ == "__main__":+ main()diff --git a/pyproject.toml b/pyproject.tomlindex fdb3cea..3edb6aa 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -72,6 +72,19 @@ markers = [target-version = "py312"line-length = 100indent-width = 4+include = [+ "fli/**/*.py",+ "examples/**/*.py",+ "tests/**/*.py",+ "scripts/**/*.py",+]+exclude = [+ "__pycache__",+ ".pytest_cache",+ ".venv",+ "build",+ "dist",+][tool.ruff.lint]select = [@@ -85,7 +98,22 @@ select = []ignore = ["D100", "D104", "D203", "D213"]+# Per-file ignores for examples+[tool.ruff.lint.per-file-ignores]+"examples/**/*.py" = [+ "D101", # Missing docstring in public class+ "D102", # Missing docstring in public method+ "D103", # Missing docstring in public function+ "D401", # First line should be in imperative mood (examples use descriptive docstrings)+ "T201", # print found (examples are meant to print output)+]+"tests/**/*.py" = [+ "D101", # Missing docstring in public class+ "D102", # Missing docstring in public method+ "D103", # Missing docstring in public function+]+[tool.ruff.format]indent-style = "space"quote-style = "double"-skip-magic-trailing-comma = false\ No newline at end of file+skip-magic-trailing-comma = false