PIbd-32_Kashin_M.I_API_Cour.../router_flight.py

44 lines
2.0 KiB
Python

from fastapi import APIRouter, HTTPException
from genetic_algorithm.genetic_algorithm import genetic_algorithm, load_graph_from_request
from schemas import TripRequest, FlightSegment, TripResult, TripOption
router = APIRouter(
prefix="/flight",
tags=["Flight"],
)
@router.post("/get/", response_model=TripResult)
async def get_flight(request: TripRequest):
graphTo, graphBack, start_point, end_point, flightsDataTo, flightsDataBack, departure_date, departure_date_return = load_graph_from_request(
request)
if request.returnDate:
resultTo = genetic_algorithm(start=start_point, end=end_point, graph=graphTo, flights_data=flightsDataTo,
type="to", departure_date=departure_date)
resultFrom = genetic_algorithm(start=end_point, end=start_point, graph=graphBack, flights_data=flightsDataBack,
type="back", departure_date=departure_date_return)
if not resultTo or not resultFrom:
raise HTTPException(status_code=404, detail="No valid paths found")
trip_options = []
for to_trip in resultTo:
for back_trip in resultFrom:
to_segments = [FlightSegment(**segment) for segment in to_trip["to"]]
back_segments = [FlightSegment(**segment) for segment in back_trip["back"]]
trip_options.append(TripOption(to=to_segments, back=back_segments))
return TripResult(trips=trip_options)
else:
resultTo = genetic_algorithm(start=start_point, end=end_point, graph=graphTo, flights_data=flightsDataTo,
type="to", departure_date=departure_date)
if not resultTo:
raise HTTPException(status_code=404, detail="No valid paths found")
trip_options = [TripOption(to=[FlightSegment(**segment) for segment in trip["to"]], back=[]) for trip in
resultTo]
return TripResult(trips=trip_options)