Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

Update code docs, format and fix lint

Punit Arani1db73bb39a4d
diff --git a/fli/cli/commands/cheap.py b/fli/cli/commands/cheap.py
index 8a16769..c82aa21 100644
--- a/fli/cli/commands/cheap.py
+++ b/fli/cli/commands/cheap.py
@@ -1,8 +1,7 @@
from datetime import datetime, timedelta
-from typing import Optional
+from typing import Annotated
import typer
-from typing_extensions import Annotated
from fli.cli.enums import DayOfWeek
from fli.cli.utils import (
@@ -112,7 +111,7 @@ def cheap(
),
] = False,
time: Annotated[
- Optional[str],
+ str | None,
typer.Option(
"--time",
"-t",
@@ -121,15 +120,11 @@ def cheap(
),
] = None,
):
- """
- Find the cheapest dates to fly between two airports.
-
- Examples:\n
- fli cheap JFK LHR\n
- fli cheap SFO NYC --from 2025-01-01 --to 2025-02-01\n
- fli cheap LAX MIA --seat BUSINESS --stops NON_STOP\n
- fli cheap JFK LHR --monday --friday # Only show Monday and Friday flights\n
- fli cheap SFO NYC --monday --wednesday --friday # Show weekday options
+ """Find the cheapest dates to fly between two airports.
+
+ Example:
+ fli cheap LAX MIA --seat BUSINESS --stops NON_STOP --friday
+
"""
try:
# Parse parameters
@@ -212,4 +207,4 @@ def cheap(
except (AttributeError, ValueError) as e:
typer.echo(f"Error: {str(e)}")
- raise typer.Exit(1)
+ raise typer.Exit(1) from e
diff --git a/fli/cli/commands/search.py b/fli/cli/commands/search.py
index 72add55..c2aa970 100644
--- a/fli/cli/commands/search.py
+++ b/fli/cli/commands/search.py
@@ -1,7 +1,6 @@
-from typing import List, Optional
+from typing import Annotated
import typer
-from typing_extensions import Annotated
from fli.cli.utils import (
display_flight_results,
@@ -20,8 +19,8 @@ def search_flights(
from_airport: str,
to_airport: str,
date: str,
- time: Optional[tuple[int, int]] = None,
- airlines: Optional[List[str]] = None,
+ time: tuple[int, int] | None = None,
+ airlines: list[str] | None = None,
seat: str = "ECONOMY",
stops: str = "ANY",
sort: str = "CHEAPEST",
@@ -69,7 +68,7 @@ def search_flights(
except (AttributeError, ValueError) as e:
typer.echo(f"Error: {str(e)}")
- raise typer.Exit(1)
+ raise typer.Exit(1) from e
def search(
@@ -77,7 +76,7 @@ def search(
to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)],
time: Annotated[
- Optional[str],
+ str | None,
typer.Option(
"--time",
"-t",
@@ -86,7 +85,7 @@ def search(
),
] = None,
airlines: Annotated[
- Optional[List[str]],
+ list[str] | None,
typer.Option(
"--airlines",
"-a",
@@ -118,13 +117,11 @@ def search(
),
] = "CHEAPEST",
):
- """
- Search for flights with flexible filtering options.
+ """Search for flights with flexible filtering options.
+
+ Example:
+ fli search JFK LHR 2025-10-25 --time 6-20 --airlines BA KL --stops NON_STOP
- Examples:\n
- fli search JFK LHR 2025-10-25 --time 6-20 --airlines BA KL\n
- fli search SFO NYC 2025-11-01 -t 9-17 --stops NON_STOP --sort DURATION\n
- fli search LAX MIA 2025-12-25 --seat BUSINESS
"""
search_flights(
from_airport=from_airport,
diff --git a/fli/cli/main.py b/fli/cli/main.py
index d6f9b75..19f79c7 100644
--- a/fli/cli/main.py
+++ b/fli/cli/main.py
@@ -6,7 +6,6 @@ import typer
from fli.cli.commands.cheap import cheap
from fli.cli.commands.search import search
-from fli.cli.console import console
app = typer.Typer(
help="Search for flights using Google Flights data",
@@ -20,8 +19,8 @@ app.command(name="cheap")(cheap)
@app.callback(invoke_without_command=True)
def main(ctx: typer.Context):
- """
- Search for flights using Google Flights data.
+ """Search for flights using Google Flights data.
+
If no command is provided, the search command will be used.
"""
# If no command is provided, show help
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
index a13630e..6f4e9ed 100644
--- a/fli/cli/utils.py
+++ b/fli/cli/utils.py
@@ -1,5 +1,4 @@
from datetime import datetime
-from typing import List, Optional
import typer
from click import Context, Parameter
@@ -19,13 +18,13 @@ def validate_date(ctx: Context, param: Parameter, value: str) -> str:
try:
datetime.strptime(value, "%Y-%m-%d")
return value
- except ValueError:
- raise typer.BadParameter("Date must be in YYYY-MM-DD format")
+ except ValueError as e:
+ raise typer.BadParameter("Date must be in YYYY-MM-DD format") from e
def validate_time_range(
- ctx: Context, param: Parameter, value: Optional[str]
-) -> Optional[tuple[int, int]]:
+ ctx: Context, param: Parameter, value: str | None
+) -> tuple[int, int] | None:
"""Validate and parse time range in format 'start-end' (24h format)."""
if not value:
return None
@@ -35,8 +34,8 @@ def validate_time_range(
if not (0 <= start <= 23 and 0 <= end <= 23):
raise ValueError
return start, end
- except ValueError:
- raise typer.BadParameter("Time range must be in format 'start-end' (e.g., 6-20)")
+ except ValueError as e:
+ raise typer.BadParameter("Time range must be in format 'start-end' (e.g., 6-20)") from e
def parse_stops(stops: str) -> MaxStops:
@@ -56,11 +55,11 @@ def parse_stops(stops: str) -> MaxStops:
# If not an integer, try as enum string
try:
return getattr(MaxStops, stops.upper())
- except AttributeError:
- raise ValueError(f"Invalid stops value: {stops}")
+ except AttributeError as e:
+ raise typer.BadParameter(f"Invalid stops value: {stops}") from e
-def parse_airlines(airlines: Optional[List[str]]) -> Optional[List[Airline]]:
+def parse_airlines(airlines: list[str] | None) -> list[Airline] | None:
"""Parse airlines from list of airline codes."""
if not airlines:
return None
@@ -70,7 +69,7 @@ def parse_airlines(airlines: Optional[List[str]]) -> Optional[List[Airline]]:
getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()
]
except AttributeError as e:
- raise typer.BadParameter(f"Invalid airline code: {str(e)}")
+ raise typer.BadParameter(f"Invalid airline code: {str(e)}") from e
def filter_flights_by_time(flights: list, start_hour: int, end_hour: int) -> list:
@@ -82,12 +81,12 @@ def filter_flights_by_time(flights: list, start_hour: int, end_hour: int) -> lis
]
-def filter_flights_by_airlines(flights: list, airlines: List[Airline]) -> list:
+def filter_flights_by_airlines(flights: list, airlines: list[Airline]) -> list:
"""Filter flights by specified airlines."""
return [flight for flight in flights if any(leg.airline in airlines for leg in flight.legs)]
-def filter_dates_by_days(dates: list, days: List[DayOfWeek]) -> list:
+def filter_dates_by_days(dates: list, days: list[DayOfWeek]) -> list:
"""Filter dates by days of the week."""
if not days:
return dates
diff --git a/fli/models/airline.py b/fli/models/airline.py
index 65f6ce8..2d63872 100644
--- a/fli/models/airline.py
+++ b/fli/models/airline.py
@@ -2,6 +2,11 @@ from enum import Enum
class Airline(Enum):
+ """Airline codes for most airlines in the world.
+
+ This is auto-generated from data/airlines.csv.
+ """
+
A0 = "Macair Jet"
A1 = "APG Distribution System"
A2 = "Astra Airlines"
diff --git a/fli/models/airport.py b/fli/models/airport.py
index 6ab3831..c7a4405 100644
--- a/fli/models/airport.py
+++ b/fli/models/airport.py
@@ -2,6 +2,11 @@ from enum import Enum
class Airport(Enum):
+ """Airport codes for most airports in the world.
+
+ This is auto-generated from data/airports.csv.
+ """
+
AAA = "Anaa"
AAB = "Arrabury Airport"
AAC = "El Arish International Airport"
diff --git a/fli/models/google_flights.py b/fli/models/google_flights.py
index aafe3ff..8735345 100644
--- a/fli/models/google_flights.py
+++ b/fli/models/google_flights.py
@@ -1,8 +1,13 @@
+"""Models for interacting with Google Flights API.
+
+This module contains all the data models used for flight searches and results.
+Models are designed to match Google Flights' APIs while providing a clean pythonic interface.
+"""
+
import json
import urllib.parse
from datetime import datetime
from enum import Enum
-from typing import List, Optional, Union
from pydantic import BaseModel, NonNegativeFloat, NonNegativeInt, PositiveInt
@@ -11,6 +16,8 @@ from .airport import Airport
class SeatType(Enum):
+ """Available cabin classes for flights."""
+
ECONOMY = 1
PREMIUM_ECONOMY = 2
BUSINESS = 3
@@ -18,6 +25,8 @@ class SeatType(Enum):
class SortBy(Enum):
+ """Available sorting options for flight results."""
+
NONE = 0
TOP_FLIGHTS = 1
CHEAPEST = 2
@@ -27,14 +36,18 @@ class SortBy(Enum):
class TripType(Enum):
+ """Type of flight journey. Currently only supports one-way flights."""
+
ONE_WAY = 2
- # Deprecated - kept for reference
+ # Currently not supported - kept for future reference
_ROUND_TRIP = 1 # Deprecated
_MULTI_CITY = 3 # Deprecated
class MaxStops(Enum):
+ """Maximum number of stops allowed in flight search."""
+
ANY = 0
NON_STOP = 1
ONE_STOP_OR_FEWER = 2
@@ -42,18 +55,27 @@ class MaxStops(Enum):
class Currency(Enum):
+ """Supported currencies for pricing. Currently only USD."""
+
USD = "USD"
# Placeholder for other currencies
class TimeRestrictions(BaseModel):
- earliest_departure: Optional[NonNegativeInt]
- latest_departure: Optional[PositiveInt]
- earliest_arrival: Optional[NonNegativeInt]
- latest_arrival: Optional[PositiveInt]
+ """Time constraints for flight departure and arrival in local time.
+
+ All times are in hours from midnight (e.g., 20 = 8:00 PM).
+ """
+
+ earliest_departure: NonNegativeInt | None = None
+ latest_departure: PositiveInt | None = None
+ earliest_arrival: NonNegativeInt | None = None
+ latest_arrival: PositiveInt | None = None
class PassengerInfo(BaseModel):
+ """Passenger configuration for flight search."""
+
adults: NonNegativeInt = 1
children: NonNegativeInt = 0
infants_in_seat: NonNegativeInt = 0
@@ -61,52 +83,85 @@ class PassengerInfo(BaseModel):
class PriceLimit(BaseModel):
+ """Maximum price constraint for flight search."""
+
max_price: PositiveInt
- currency: Optional[Currency] = Currency.USD
+ currency: Currency | None = Currency.USD
class LayoverRestrictions(BaseModel):
- airports: Optional[List[Airport]]
- max_duration: Optional[PositiveInt]
+ """Constraints for layovers in multi-leg flights."""
+
+ airports: list[Airport] | None = None
+ max_duration: PositiveInt | None = None
class FlightSegment(BaseModel):
- departure_airport: List[List[Union[Airport, int]]]
- arrival_airport: List[List[Union[Airport, int]]]
+ """A segment represents a single portion of a flight journey between two airports.
+
+ For example, in a one-way flight from JFK to LAX, there would be one segment.
+ In a multi-city trip from JFK -> LAX -> SEA, there would be two segments:
+ JFK -> LAX and LAX -> SEA.
+ """
+
+ departure_airport: list[list[Airport | int]]
+ arrival_airport: list[list[Airport | int]]
travel_date: str
- time_restrictions: Optional[TimeRestrictions] = None
+ time_restrictions: TimeRestrictions | None = None
class FlightLeg(BaseModel):
+ """A single flight leg (segment) with airline and timing details."""
+
airline: Airline
flight_number: str
departure_airport: Airport
arrival_airport: Airport
departure_datetime: datetime
arrival_datetime: datetime
- duration: PositiveInt
+ duration: PositiveInt # in minutes
class FlightResult(BaseModel):
- legs: List[FlightLeg]
- price: NonNegativeFloat
- duration: PositiveInt
+ """Complete flight search result with pricing and timing."""
+
+ legs: list[FlightLeg]
+ price: NonNegativeFloat # in specified currency
+ duration: PositiveInt # total duration in minutes
stops: NonNegativeInt
class FlightSearchFilters(BaseModel):
+ """Complete set of filters for flight search.
+
+ This model matches required Google Flights' API structure.
+ """
+
trip_type: TripType = TripType.ONE_WAY
passenger_info: PassengerInfo
- flight_segments: List[FlightSegment]
+ flight_segments: list[FlightSegment]
stops: MaxStops = MaxStops.ANY
seat_type: SeatType = SeatType.ECONOMY
- price_limit: Optional[PriceLimit] = None
- airlines: Optional[List[Airline]] = None
- max_duration: Optional[PositiveInt] = None
- layover_restrictions: Optional[LayoverRestrictions] = None
+ price_limit: PriceLimit | None = None
+ airlines: list[Airline] | None = None
+ max_duration: PositiveInt | None = None # in minutes
+ layover_restrictions: LayoverRestrictions | None = None
sort_by: SortBy = SortBy.NONE
def format(self) -> list:
+ """Format filters into Google Flights API structure.
+
+ This method converts the FlightSearchFilters model into the specific nested list/dict
+ structure required by Google Flights' API.
+
+ The output format matches Google Flights' internal API structure, with careful handling
+ of nested arrays and proper serialization of enums and model objects.
+
+ Returns:
+ list: A formatted list structure ready for the Google Flights API request
+
+ """
+
def serialize(obj):
if isinstance(obj, Airport) or isinstance(obj, Airline):
return obj.name
@@ -222,7 +277,7 @@ class FlightSearchFilters(BaseModel):
return filters
def encode(self) -> str:
- """Format and URL encode the filters."""
+ """URL encode the formatted filters for API request."""
formatted_filters = self.format()
# First convert the formatted filters to a JSON string
formatted_json = json.dumps(formatted_filters, separators=(",", ":"))
@@ -233,19 +288,35 @@ class FlightSearchFilters(BaseModel):
class DateSearchFilters(BaseModel):
+ """Filters for searching flights across a date range.
+
+ Similar to FlightSearchFilters but includes date range parameters
+ for finding the cheapest dates to fly.
+ """
+
trip_type: TripType = TripType.ONE_WAY
passenger_info: PassengerInfo
- flight_segments: List[FlightSegment]
+ flight_segments: list[FlightSegment]
stops: MaxStops = MaxStops.ANY
seat_type: SeatType = SeatType.ECONOMY
- price_limit: Optional[PriceLimit] = None
- airlines: Optional[List[Airline]] = None
- max_duration: Optional[PositiveInt] = None
- layover_restrictions: Optional[LayoverRestrictions] = None
- from_date: str
- to_date: str
+ price_limit: PriceLimit | None = None
+ airlines: list[Airline] | None = None
+ max_duration: PositiveInt | None = None # in minutes
+ layover_restrictions: LayoverRestrictions | None = None
+ from_date: str # YYYY-MM-DD format
+ to_date: str # YYYY-MM-DD format
def format(self) -> list:
+ """Format filters into Google Flights API structure.
+
+ This method converts the DateSearchFilters model into the specific nested list/dict
+ structure required by Google Flights' API.
+
+ Returns:
+ list: A formatted list structure ready for the Google Flights API request
+
+ """
+
def serialize(obj):
if isinstance(obj, Airport) or isinstance(obj, Airline):
return obj.name
@@ -361,7 +432,7 @@ class DateSearchFilters(BaseModel):
return filters
def encode(self) -> str:
- """Format and URL encode the filters."""
+ """URL encode the formatted filters for API request."""
formatted_filters = self.format()
# First convert the formatted filters to a JSON string
formatted_json = json.dumps(formatted_filters, separators=(",", ":"))
diff --git a/fli/search/client.py b/fli/search/client.py
index 0cbadc7..e5d9d50 100644
--- a/fli/search/client.py
+++ b/fli/search/client.py
@@ -1,3 +1,13 @@
+"""HTTP client implementation with impersonation, rate limiting and retry functionality.
+
+This module provides a robust HTTP client that handles:
+- User agent impersonation (to mimic a browser)
+- Rate limiting (10 requests per second)
+- Automatic retries with exponential backoff
+- Session management
+- Error handling
+"""
+
from curl_cffi import requests
from ratelimit import limits, sleep_and_retry
from tenacity import retry, stop_after_attempt, wait_exponential
@@ -6,19 +16,19 @@ client = None
class Client:
- """Base HTTP client with rate limiting and retry functionality."""
+ """HTTP client with built-in rate limiting, retry and user agent impersonation functionality."""
DEFAULT_HEADERS = {
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
}
def __init__(self):
- """Initialize the client."""
+ """Initialize a new client session with default headers."""
self._client = requests.Session()
self._client.headers.update(self.DEFAULT_HEADERS)
def __del__(self):
- """Cleanup client session."""
+ """Clean up client session on deletion."""
if hasattr(self, "_client"):
self._client.close()
@@ -26,18 +36,18 @@ class Client:
@limits(calls=10, period=1)
@retry(stop=stop_after_attempt(3), wait=wait_exponential(), reraise=True)
def get(self, url: str, **kwargs) -> requests.Response:
- """
- Make a rate-limited GET request with automatic retries.
+ """Make a rate-limited GET request with automatic retries.
Args:
- url: The URL to request.
- **kwargs: Additional arguments to pass to the request.
+ url: Target URL for the request
+ **kwargs: Additional arguments passed to requests.get()
Returns:
- The response from the server.
+ Response object from the server
Raises:
- Exception: If the request fails after retries.
+ Exception: If request fails after all retries
+
"""
try:
response = self._client.get(url, **kwargs)
@@ -50,18 +60,18 @@ class Client:
@limits(calls=10, period=1)
@retry(stop=stop_after_attempt(3), wait=wait_exponential(), reraise=True)
def post(self, url: str, **kwargs) -> requests.Response:
- """
- Make a rate-limited POST request with automatic retries.
+ """Make a rate-limited POST request with automatic retries.
Args:
- url: The URL to request.
- **kwargs: Additional arguments to pass to the request.
+ url: Target URL for the request
+ **kwargs: Additional arguments passed to requests.post()
Returns:
- The response from the server.
+ Response object from the server
Raises:
- Exception: If the request fails after retries.
+ Exception: If request fails after all retries
+
"""
try:
response = self._client.post(url, **kwargs)
@@ -72,7 +82,12 @@ class Client:
def get_client() -> Client:
- """Get the shared HTTP client instance."""
+ """Get or create a shared HTTP client instance.
+
+ Returns:
+ Singleton instance of the HTTP client
+
+ """
global client
if not client:
client = Client()
diff --git a/fli/search/dates.py b/fli/search/dates.py
index 0afaef3..d13a800 100644
--- a/fli/search/dates.py
+++ b/fli/search/dates.py
@@ -1,4 +1,11 @@
-"""Date search implementation."""
+"""Date-based flight search implementation for finding the cheapest dates to fly.
+
+This module provides functionality to search for the cheapest flights across a date range.
+It uses Google Flights' calendar view API to find the best prices for each date.
+It is intended to be used for finding the cheapest dates to fly, not the cheapest flights.
+
+Currently only supports one-way flights.
+"""
import json
from datetime import datetime
@@ -10,12 +17,18 @@ from fli.search.client import get_client
class DatePrice(BaseModel):
+ """Flight price for a specific date."""
+
date: datetime
price: float
class SearchDates:
- """Date search implementation."""
+ """Date-based flight search implementation.
+
+ This class provides methods to search for flight prices across a date range,
+ useful for finding the cheapest dates to fly.
+ """
BASE_URL = "https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetCalendarGrid"
DEFAULT_HEADERS = {
@@ -23,23 +36,25 @@ class SearchDates:
}
def __init__(self):
- """Initialize the search client."""
+ """Initialize the search client for date-based searches."""
self.client = get_client()
def search(self, filters: DateSearchFilters) -> list[DatePrice] | None:
- """
- Perform the date search using the search parameters.
+ """Search for flight prices across a date range and search parameters.
Args:
- filters: The search filters to use.
+ filters: Search parameters including date range, airports, and preferences
Returns:
- A list of DatePrice objects containing date and price pairs, or None if no results found.
+ List of DatePrice objects containing date and price pairs, or None if no results
+
+ Raises:
+ Exception: If the search fails or returns invalid data
+
"""
encoded_filters = filters.encode()
try:
- # Debugging
response = self.client.post(
url=self.BASE_URL,
data=f"f.req={encoded_filters}",
@@ -67,7 +82,15 @@ class SearchDates:
@staticmethod
def __parse_price(item: list[list] | list | None) -> float | None:
- """Parse the price string safely."""
+ """Parse price data from the API response.
+
+ Args:
+ item: Raw price data from the API response
+
+ Returns:
+ Float price value if valid, None if invalid or missing
+
+ """
try:
if item and isinstance(item, list) and len(item) > 2:
if isinstance(item[2], list) and len(item[2]) > 0:
diff --git a/fli/search/flights.py b/fli/search/flights.py
index 63b64df..56e344e 100644
--- a/fli/search/flights.py
+++ b/fli/search/flights.py
@@ -1,6 +1,13 @@
+"""Flight search implementation.
+
+This module provides the core flight search functionality, interfacing directly
+with Google Flights' API to find available flights and their details.
+
+Currently only supports one-way flights.
+"""
+
import json
from datetime import datetime
-from typing import List
from pydantic import BaseModel
@@ -20,6 +27,22 @@ from fli.search.client import get_client
class SearchFlightsFilters(BaseModel):
+ """Simplified search filters for flight searches.
+
+ This model provides a simpler interface compared to the full FlightSearchFilters,
+ focusing on the most common search parameters.
+
+ Attributes:
+ departure_airport: Origin airport
+ arrival_airport: Destination airport
+ departure_date: Date in YYYY-MM-DD format
+ passenger_info: Passenger configuration (defaults to 1 adult)
+ seat_type: Cabin class (defaults to economy)
+ stops: Maximum stops allowed (defaults to any)
+ sort_by: Sort criteria (defaults to cheapest)
+
+ """
+
departure_airport: Airport
arrival_airport: Airport
departure_date: str
@@ -30,7 +53,13 @@ class SearchFlightsFilters(BaseModel):
class SearchFlights:
- """Flight search implementation."""
+ """Flight search implementation using Google Flights' API.
+
+ This class handles searching for specific flights with detailed filters,
+ parsing the results into structured data models.
+
+ Currently only supports one-way flights.
+ """
BASE_URL = "https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetShoppingResults"
DEFAULT_HEADERS = {
@@ -38,12 +67,21 @@ class SearchFlights:
}
def __init__(self):
- """Initialize the search client."""
+ """Initialize the search client for flight searches."""
self.client = get_client()
- def search(self, filters: SearchFlightsFilters) -> List[FlightResult] | None:
- """
- Perform the flight search using the new simplified parameters.
+ def search(self, filters: SearchFlightsFilters) -> list[FlightResult] | None:
+ """Search for flights using the provided filters.
+
+ Args:
+ filters: Search parameters including airports, dates, and preferences
+
+ Returns:
+ List of FlightResult objects containing flight details, or None if no results
+
+ Raises:
+ Exception: If the search fails or returns invalid data
+
"""
search_filters = self._create_flight_search_data(filters)
encoded_filters = search_filters.encode()
@@ -76,8 +114,14 @@ class SearchFlights:
@staticmethod
def _create_flight_search_data(params: SearchFlightsFilters) -> FlightSearchFilters:
- """
- Helper function to convert from our simpler param model to the existing FlightSearchFilters model.
+ """Convert simplified filters to full API filters.
+
+ Args:
+ params: Simplified search parameters
+
+ Returns:
+ Complete FlightSearchFilters object ready for API use
+
"""
return FlightSearchFilters(
passenger_info=params.passenger_info,
@@ -94,7 +138,16 @@ class SearchFlights:
)
@staticmethod
- def _parse_flights_data(data: List) -> FlightResult:
+ def _parse_flights_data(data: list) -> FlightResult:
+ """Parse raw flight data into a structured FlightResult.
+
+ Args:
+ data: Raw flight data from the API response
+
+ Returns:
+ Structured FlightResult object with all flight details
+
+ """
flight = FlightResult(
price=data[1][0][-1],
duration=data[0][9],
@@ -115,21 +168,20 @@ class SearchFlights:
return flight
@staticmethod
- def _parse_datetime(date_arr: List[int], time_arr: List[int]) -> datetime:
- """
- Convert date and time arrays to datetime.
+ def _parse_datetime(date_arr: list[int], time_arr: list[int]) -> datetime:
+ """Convert date and time arrays to datetime.
Args:
- date_arr: List of integers representing the date. Ex: [2025, 1, 1] (year, month, day)
- time_arr: List of integers representing the time. Ex: [13, 45] (hour, minute)
+ date_arr: List of integers [year, month, day]
+ time_arr: List of integers [hour, minute]
Returns:
- datetime: The parsed datetime object.
+ Parsed datetime object
+
+ Raises:
+ ValueError: If arrays contain only None values
- Note:
- date and time arrays can contain None values to represent 0.
"""
- # Raise error if either date or time arrays are empty, or contain only None values
if not any(x is not None for x in date_arr) or not any(x is not None for x in time_arr):
raise ValueError("Date and time arrays must contain at least one non-None value")
@@ -137,8 +189,14 @@ class SearchFlights:
@staticmethod
def _parse_airline(airline_code: str) -> Airline:
- """
- Parse the airline code to the corresponding Airline enum.
+ """Convert airline code to Airline enum.
+
+ Args:
+ airline_code: Raw airline code from API
+
+ Returns:
+ Corresponding Airline enum value
+
"""
if airline_code[0].isdigit():
airline_code = f"_{airline_code}"
@@ -146,7 +204,13 @@ class SearchFlights:
@staticmethod
def _parse_airport(airport_code: str) -> Airport:
- """
- Parse the airport code to the corresponding Airport enum.
+ """Convert airport code to Airport enum.
+
+ Args:
+ airport_code: Raw airport code from API
+
+ Returns:
+ Corresponding Airport enum value
+
"""
return getattr(Airport, airport_code)
diff --git a/scripts/generate_enums.py b/scripts/generate_enums.py
index 20721a2..0ded566 100644
--- a/scripts/generate_enums.py
+++ b/scripts/generate_enums.py
@@ -1,4 +1,18 @@
#!/usr/bin/env python3
+"""Script to generate Airport and Airline enums from CSV data files.
+
+This script reads airport and airline data from CSV files and generates corresponding
+Python Enum classes. The generated enums are used throughout the application to ensure
+consistent handling of airport and airline codes.
+
+The script expects CSV files in the following locations:
+- data/airports.csv: Contains airport codes and names
+- data/airlines.csv: Contains airline IATA codes and names
+
+The generated enum files are written to:
+- fli/models/airport.py: Contains the Airport enum
+- fli/models/airline.py: Contains the Airline enum
+"""
import csv
from pathlib import Path
@@ -7,6 +21,16 @@ PROJECT_DIR = Path(__file__).parents[1].resolve()
def generate_airport_enum():
+ """Generate Airport enum class from airports.csv data.
+
+ Reads airport codes and names from the CSV file and generates a Python Enum class
+ with airport codes as enum members and airport names as their values.
+
+ Raises:
+ FileNotFoundError: If the airports.csv file is not found
+ ValueError: If there are errors reading or parsing the CSV file
+
+ """
airport_csv_path = PROJECT_DIR.joinpath("data", "airports.csv")
airport_enum_path = PROJECT_DIR.joinpath("fli", "models", "airport.py")
@@ -16,11 +40,11 @@ def generate_airport_enum():
# Read airport entries from CSV
try:
- with open(airport_csv_path, "r", encoding="utf-8") as csv_file:
+ with open(airport_csv_path, encoding="utf-8") as csv_file:
reader = csv.DictReader(csv_file)
entries = [(row["Code"].strip().upper(), row["Name"].strip()) for row in reader]
except (KeyError, csv.Error) as e:
- raise ValueError(f"Error reading CSV file: {e}")
+ raise ValueError(f"Error reading CSV file: {e}") from e
# Ensure output directory exists
airport_enum_path.parent.mkdir(parents=True, exist_ok=True)
@@ -39,6 +63,17 @@ def generate_airport_enum():
def generate_airline_enum():
+ """Generate Airline enum class from airlines.csv data.
+
+ Reads airline IATA codes and names from the CSV file and generates a Python Enum class
+ with airline codes as enum members and airline names as their values. Handles cases
+ where airline codes start with numbers by prefixing them with an underscore.
+
+ Raises:
+ FileNotFoundError: If the airlines.csv file is not found
+ ValueError: If there are errors reading or parsing the CSV file
+
+ """
airline_csv_path = PROJECT_DIR.joinpath("data", "airlines.csv")
airline_enum_path = PROJECT_DIR.joinpath("fli", "models", "airline.py")
@@ -48,11 +83,11 @@ def generate_airline_enum():
# Read airline entries from CSV
try:
- with open(airline_csv_path, "r", encoding="utf-8") as csv_file:
+ with open(airline_csv_path, encoding="utf-8") as csv_file:
reader = csv.DictReader(csv_file)
entries = [(row["IATA"].strip().upper(), row["Airline"].strip()) for row in reader]
except (KeyError, csv.Error) as e:
- raise ValueError(f"Error reading CSV file: {e}")
+ raise ValueError(f"Error reading CSV file: {e}") from e
# Ensure output directory exists
airline_enum_path.parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/conftest.py b/tests/conftest.py
index b733051..346f5da 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,12 +1,13 @@
import pytest
-def pytest_addoption(parser):
+def pytest_addoption(parser) -> None:
+ """Add options to pytest."""
parser.addoption("--fuzz", action="store_true", help="Run fuzz tests")
parser.addoption("--all", action="store_true", help="Run all tests")
-def pytest_runtest_setup(item):
+def pytest_runtest_setup(item) -> None:
"""Skip fuzz tests unless --fuzz or --all is specified."""
fuzz_marker = item.get_closest_marker("fuzz")
if fuzz_marker is not None:
diff --git a/tests/models/test_flight_search_filters.py b/tests/models/test_flight_search_filters.py
index 69bd74c..ff9f022 100644
--- a/tests/models/test_flight_search_filters.py
+++ b/tests/models/test_flight_search_filters.py
@@ -231,7 +231,7 @@ TEST_CASES = [
0,
2,
],
- "encoded": "%5Bnull%2C%22%5B%5B%5D%2C%5Bnull%2Cnull%2C2%2Cnull%2C%5B%5D%2C1%2C%5B2%2C3%2C1%2C0%5D%2C%5Bnull%2C900%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5B%5B%5B%5B%5C%22PHX%5C%22%2C0%5D%5D%5D%2C%5B%5B%5B%5C%22SFO%5C%22%2C0%5D%5D%5D%2C%5B9%2C20%2C13%2C21%5D%2C0%2C%5B%5C%22AA%5C%22%2C%5C%22F9%5C%22%2C%5C%22UA%5C%22%5D%2Cnull%2C%5C%222025-06-01%5C%22%2C%5B660%5D%2Cnull%2C%5B%5C%22LAX%5C%22%5D%2Cnull%2Cnull%2C420%2Cnull%2C3%5D%5D%2Cnull%2Cnull%2Cnull%2C1%5D%2C0%2C0%2C0%2C2%5D%22%5D",
+ "encoded": "%5Bnull%2C%22%5B%5B%5D%2C%5Bnull%2Cnull%2C2%2Cnull%2C%5B%5D%2C1%2C%5B2%2C3%2C1%2C0%5D%2C%5Bnull%2C900%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5B%5B%5B%5B%5C%22PHX%5C%22%2C0%5D%5D%5D%2C%5B%5B%5B%5C%22SFO%5C%22%2C0%5D%5D%5D%2C%5B9%2C20%2C13%2C21%5D%2C0%2C%5B%5C%22AA%5C%22%2C%5C%22F9%5C%22%2C%5C%22UA%5C%22%5D%2Cnull%2C%5C%222025-06-01%5C%22%2C%5B660%5D%2Cnull%2C%5B%5C%22LAX%5C%22%5D%2Cnull%2Cnull%2C420%2Cnull%2C3%5D%5D%2Cnull%2Cnull%2Cnull%2C1%5D%2C0%2C0%2C0%2C2%5D%22%5D", # noqa: E501
},
]
diff --git a/tests/search/test_search_flights_fuzz.py b/tests/search/test_search_flights_fuzz.py
index bc0b8bf..d940ecd 100644
--- a/tests/search/test_search_flights_fuzz.py
+++ b/tests/search/test_search_flights_fuzz.py
@@ -2,7 +2,6 @@
import random
from datetime import datetime, timedelta
-from typing import List, Tuple
import pytest
@@ -33,7 +32,7 @@ def generate_test_id(val, argname=None, idx=None) -> str:
return str(val)
-def generate_random_test_cases(num_tests: int) -> List[Tuple]:
+def generate_random_test_cases(num_tests: int) -> list[tuple]:
"""Generate randomized test cases for fuzz testing."""
random.seed(42)
airports = list(Airport)
@@ -82,7 +81,7 @@ def generate_random_test_cases(num_tests: int) -> List[Tuple]:
@pytest.mark.fuzz
@pytest.mark.parallel
@pytest.mark.parametrize(
- "dep_airport, arr_airport, dep_date, adults, children, infants_on_lap, infants_in_seat, seat_type, stops, sort_by",
+ "dep_airport, arr_airport, dep_date, adults, children, infants_on_lap, infants_in_seat, seat_type, stops, sort_by", # noqa: E501
generate_random_test_cases(num_tests=100),
ids=generate_test_id,
)
@@ -99,8 +98,8 @@ def test_search_fuzz(
stops: MaxStops,
sort_by: SortBy,
):
- """
- Parameterized fuzz test for flight search with various filter combinations.
+ """Parameterized fuzz test for flight search with various filter combinations.
+
Designed to run in parallel using pytest-xdist.
"""
passenger_info = PassengerInfo(