Last active
May 23, 2024 04:40
-
-
Save janakiramm/2143b909626f5f01d64739e3fe90c9c8 to your computer and use it in GitHub Desktop.
Function to Invoke FlightAware API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
import json | |
import random | |
from datetime import datetime, timedelta | |
import requests | |
import pytz | |
def get_flight_status(flight): | |
"""Returns Flight Information""" | |
AEROAPI_BASE_URL = "https://aeroapi.flightaware.com/aeroapi" | |
AEROAPI_KEY="YOUR FLIGHTAWARE API KEY" | |
def get_api_session(): | |
session = requests.Session() | |
session.headers.update({"x-apikey": AEROAPI_KEY}) | |
return session | |
def fetch_flight_data(flight_id, session): | |
if "flight_id=" in flight_id: | |
flight_id = flight_id.split("flight_id=")[1] | |
start_date = datetime.now().date().strftime('%Y-%m-%d') | |
end_date = (datetime.now().date() + timedelta(days=1)).strftime('%Y-%m-%d') | |
api_resource = f"/flights/{flight_id}?start={start_date}&end={end_date}" | |
response = session.get(f"{AEROAPI_BASE_URL}{api_resource}") | |
response.raise_for_status() | |
return response.json()['flights'][0] | |
def utc_to_local(utc_date_str, local_timezone_str): | |
utc_datetime = datetime.strptime(utc_date_str, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.utc) | |
local_timezone = pytz.timezone(local_timezone_str) | |
local_datetime = utc_datetime.astimezone(local_timezone) | |
return local_datetime.strftime('%Y-%m-%d %H:%M:%S') | |
session = get_api_session() | |
flight_data = fetch_flight_data(flight, session) | |
dep_key = 'estimated_out' if 'estimated_out' in flight_data and flight_data['estimated_out'] else \ | |
'actual_out' if 'actual_out' in flight_data and flight_data['actual_out'] else \ | |
'scheduled_out' | |
arr_key = 'estimated_in' if 'estimated_in' in flight_data and flight_data['estimated_in'] else \ | |
'actual_in' if 'actual_in' in flight_data and flight_data['actual_in'] else \ | |
'scheduled_in' | |
flight_details = { | |
'flight':flight, | |
'source': flight_data['origin']['city'], | |
'destination': flight_data['destination']['city'], | |
'depart_time': utc_to_local(flight_data[dep_key], flight_data['origin']['timezone']), | |
'arrival_time': utc_to_local(flight_data[arr_key], flight_data['destination']['timezone']), | |
'status': flight_data['status'] | |
} | |
return json.dumps(flight_details) | |
flight_info = get_flight_status("EK524") | |
print(flight_info) | |
#'{"flight": "EK524", "source": "Dubai", "destination": "Hyderabad", "depart_time": "2024-05-23 22:00:00", "arrival_time": "2024-05-24 03:05:00", "status": "Scheduled"}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment