### Install pyopensky with pip Source: https://github.com/open-aviation/pyopensky/blob/master/docs/source/installation.rst Installs the pyopensky library using pip, the standard Python package installer. This is the most common method for installing Python packages. ```bash pip install pyopensky ``` -------------------------------- ### Install uv and pyopensky in development mode Source: https://github.com/open-aviation/pyopensky/blob/master/docs/source/installation.rst Installs the uv tool and then synchronizes dependencies in development mode, which includes pyopensky. This method is suitable for developers contributing to the project. ```bash # Linux and MacOS curl -LsSf https://astral.sh/uv/install.sh | sh # Windows irm https://astral.sh/uv/install.ps1 | iex uv sync --dev ``` -------------------------------- ### Install pyopensky with conda Source: https://github.com/open-aviation/pyopensky/blob/master/docs/source/installation.rst Installs the pyopensky library from the conda-forge channel using the conda package manager. This is useful for users who manage their environments with Conda. ```bash conda install -c conda-forge pyopensky ``` -------------------------------- ### Install pyopensky Python Library Source: https://github.com/open-aviation/pyopensky/blob/master/readme.md Installs the pyopensky Python library using pip or conda-forge. Development mode installation is also shown using uv. ```shell pip install pyopensky ``` ```shell conda install -c conda-forge pyopensky ``` ```shell curl -LsSf https://astral.sh/uv/install.sh | sh # Linux and MacOS irm https://astral.sh/uv/install.ps1 | iex # Windows uv sync --dev ``` -------------------------------- ### Trino Query Error Handling (Queue Full) - Python Source: https://context7.com/open-aviation/pyopensky/llms.txt Shows how to handle potential runtime errors when querying the Trino service, specifically addressing the 'QUERY_QUEUE_FULL' error. This example provides guidance on checking the Trino UI and suggests actions like killing old queries if the queue is full. ```python from pyopensky.trino import Trino import pandas as pd trino = Trino() # Trino queries show progress and handle resource limits try: flights = trino.flightlist( pd.Timestamp("2024-01-15", tz="utc"), pd.Timestamp("2024-01-16", tz="utc"), airport="LFPG", cached=True ) # Progress bar shows: query state and download progress # Cached results avoid hitting database limits except RuntimeError as e: if "QUERY_QUEUE_FULL" in str(e): print("Too many concurrent queries. Check: https://trino.opensky-network.org/ui/") print("Kill old queries and try again") else: raise ``` -------------------------------- ### Get Pyopensky Configuration Directory Source: https://github.com/open-aviation/pyopensky/blob/master/docs/source/credentials.rst This Python code snippet demonstrates how to retrieve the directory path where the pyopensky configuration file (settings.conf) is located. It's useful for locating or managing configuration settings. ```python from pyopensky.config import opensky_config_dir print(opensky_config_dir) ``` -------------------------------- ### Get Airport Arrivals (REST API) Source: https://context7.com/open-aviation/pyopensky/llms.txt Fetches a list of flights arriving at a specific airport within a defined time range. This is useful for analyzing inbound air traffic. It requires the airport IATA code and two pandas Timestamp objects for the start and end of the period. Returns a DataFrame containing flight details. ```python from pyopensky.rest import REST import pandas as pd rest = REST() # Get arrivals at Amsterdam Schiphol for a specific day airport = "EHAM" begin = pd.Timestamp("2024-01-15", tz="utc") end = begin + pd.Timedelta("1d") arrivals = rest.arrival(airport, begin, end) # Returns DataFrame with columns: firstSeen, lastSeen, icao24, # callsign, estDepartureAirport, estArrivalAirport print(f"Total arrivals: {len(arrivals)}") for idx, flight in arrivals.iterrows(): print(f"{flight['callsign']} from {flight['estDepartureAirport']} " f"landed at {flight['lastSeen']}") ``` -------------------------------- ### Advanced Flight List Query with Filters - Python Source: https://context7.com/open-aviation/pyopensky/llms.txt Demonstrates a complex flight list query using the Trino client. This example shows how to apply multiple filters, including callsign wildcards, departure airports, custom SQL conditions on flight duration, and selecting additional columns. It also specifies limits and caching options. ```python from pyopensky.trino import Trino from pyopensky.schema import FlightsData4, StateVectorsData4 import pandas as pd trino = Trino() # Complex flight list query with multiple filters start = pd.Timestamp("2024-01-15", tz="utc") stop = pd.Timestamp("2024-01-16", tz="utc") flights = trino.flightlist( start, stop, # Multiple callsigns with wildcards callsign=["AFR%", "BAW%", "DLH%"] matters, # Any of these airports departure_airport=["LFPG", "EGLL", "EDDF"], # Custom SQL conditions FlightsData4.lastseen - FlightsData4.firstseen > 3600, # Flights > 1 hour # Additional columns to retrieve extra_columns=[FlightsData4.day], limit=500, cached=True, compress=True ) ``` -------------------------------- ### Querying History with Custom Column Selection - Python Source: https://context7.com/open-aviation/pyopensky/llms.txt Demonstrates querying flight history with a specific set of columns. This example uses the Trino client to fetch state vectors, allowing for custom selection of columns like time, coordinates, altitude, and velocity. It also shows how to disable caching for a fresh query. ```python custom_history = trino.history( start, stop, bounds=(-10, 40, 10, 55), selected_columns=( StateVectorsData4.time, StateVectorsData4.icao24, StateVectorsData4.lat, StateVectorsData4.lon, StateVectorsData4.altitude, "StateVectorsData4.velocity" # Can also use string format ), cached=False # Force fresh query, bypass cache ) ``` -------------------------------- ### Get Raw ADS-B Messages for Callsign (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve raw ADS-B messages for flights with a specific callsign. Options for caching and compressing cache files are available. ```python raw_callsign = trino.rawdata( start, stop, callsign="BAW123", compress=True ) ``` -------------------------------- ### Get Aircraft Flight History (REST API) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieves all recorded flights for a specific aircraft (identified by ICAO24) within a specified date range. This is useful for analyzing an individual aircraft's activity over time. It requires the aircraft's ICAO24 address and pandas Timestamps for the start and end dates. The output is a DataFrame detailing each flight. ```python from pyopensky.rest import REST import pandas as pd rest = REST() # Get flight history for aircraft icao24 = "a12345" begin = pd.Timestamp("2024-01-15", tz="utc") end = pd.Timestamp("2024-01-22", tz="utc") flights = rest.aircraft(icao24, begin, end) # Analyze the aircraft's weekly activity print(f"Flights in period: {len(flights)}") for idx, flight in flights.iterrows(): duration = (flight['lastSeen'] - flight['firstSeen']).total_seconds() / 3600 print(f"{flight['callsign']}: {flight['estDepartureAirport']} -> " f"{flight['estArrivalAirport']} ({duration:.1f} hours)") ``` -------------------------------- ### Get Airport Departures (REST API) Source: https://context7.com/open-aviation/pyopensky/llms.txt Queries flights departing from a specific airport within a given time range. This function helps in analyzing outbound air traffic. It requires the airport IATA code and pandas Timestamps for the start and end times. The resulting DataFrame can be filtered by carrier or sorted by departure time. ```python from pyopensky.rest import REST import pandas as pd rest = REST() # Get departures from London Heathrow airport = "EGLL" begin = pd.Timestamp("2024-01-15 06:00:00", tz="utc") end = pd.Timestamp("2024-01-15 18:00:00", tz="utc") departures = rest.departure(airport, begin, end) # Filter specific carrier british_airways = departures[departures['callsign'].str.startswith('BAW')] print(f"British Airways departures: {len(british_airways)}") # Sort by departure time departures_sorted = departures.sort_values('firstSeen') ``` -------------------------------- ### Get Raw ADS-B Messages for Aircraft (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve raw Mode S and ADS-B messages for a specific aircraft identified by its ICAO24 address within a given time range. The `cached` option is available. ```python raw_messages = trino.rawdata( start, stop, icao24="a12345", cached=True ) ``` -------------------------------- ### Get Raw ADS-B Messages in Geographic Area (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve raw ADS-B messages within a specified geographic bounding box. A limit can be set for the number of messages returned. ```python bounds = (-5.0, 50.0, 2.0, 52.0) raw_area = trino.rawdata( start, stop, bounds=bounds, limit=1000 ) ``` -------------------------------- ### Get Current Aircraft States (REST API) Source: https://context7.com/open-aviation/pyopensky/llms.txt Fetches real-time aircraft positions and state information globally or within a specified geographic bounding box using the OpenSky Network REST API. Requires no authentication for public data. Returns a pandas DataFrame with detailed aircraft information. ```python from pyopensky.rest import REST rest = REST() # Get all current state vectors worldwide states = rest.states() print(states.head()) # Returns DataFrame with columns: icao24, callsign, origin_country, # timestamp, longitude, latitude, altitude, onground, groundspeed, # track, vertical_rate, sensors, geoaltitude, squawk, spi, position_source # Get state vectors for a specific geographic area (bounds: west, south, east, north) states_france = rest.states(bounds=(2.0, 42.0, 8.0, 51.0)) # Get state vectors for own sensors (requires authentication) states_own = rest.states(own=True) ``` -------------------------------- ### Get Historical Trajectory Data (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve detailed historical trajectory data, including position, altitude, and velocity, for a specific flight identified by its callsign. The `cached` option can be used to leverage local cache. ```python trajectory = trino.history( start, stop, callsign="AFR1234", cached=True ) ``` -------------------------------- ### Query Historical Flight Lists (Trino Database) Source: https://context7.com/open-aviation/pyopensky/llms.txt Queries historical flight lists from the OpenSky Network's Trino database, allowing for advanced filtering. This method requires initializing the `Trino` client, potentially with credentials. It accepts start and stop timestamps and optional filters like airport code. The `cached` parameter can be used to prioritize cached results. Returns a pandas DataFrame of flights. ```python from pyopensky.trino import Trino import pandas as pd # Initialize with credentials from config or environment trino = Trino() # Get all flights for a specific airport start = pd.Timestamp("2024-01-15", tz="utc") stop = pd.Timestamp("2024-01-16", tz="utc") flights = trino.flightlist( start, stop, airport="LFPG", # Paris Charles de Gaulle cached=True ) if flights is not None: print(f"Found {len(flights)} flights") ``` -------------------------------- ### Initialize REST and Trino Clients - Python Source: https://context7.com/open-aviation/pyopensky/llms.txt Initializes the REST and Trino clients for interacting with the OpenSky Network API. Credentials are automatically loaded from environment variables, so ensure your .env file is properly configured. ```python from pyopensky.rest import REST from pyopensky.trino import Trino # Credentials are automatically loaded rest = REST() trino = Trino() ``` -------------------------------- ### Configure OpenSky Credentials via Settings File Source: https://context7.com/open-aviation/pyopensky/llms.txt Set up authentication for OpenSky services by creating a configuration file (e.g., ~/.config/pyopensky/settings.conf) with credentials for default access, Trino, S3, and cache settings. ```ini [default] username = your_username password = your_password client_id = your_client_id client_secret = your_client_secret [trino] username = your_trino_username password = your_trino_password [s3] access_key = your_s3_access_key secret_key = your_s3_secret_key [cache] path = /custom/cache/path purge = 90 days ``` -------------------------------- ### Configure OpenSky Credentials via Environment Variables Source: https://context7.com/open-aviation/pyopensky/llms.txt Set up authentication for OpenSky services by defining environment variables for username, password, client ID, client secret, and specific credentials for Trino and S3 access. ```python # Method 1: Environment variables (recommended) import os os.environ['OPENSKY_USERNAME'] = 'your_username' os.environ['OPENSKY_PASSWORD'] = 'your_password' os.environ['OPENSKY_CLIENT_ID'] = 'your_client_id' os.environ['OPENSKY_CLIENT_SECRET'] = 'your_client_secret' # For Trino database access os.environ['OPENSKY_TRINO_USERNAME'] = 'your_trino_username' os.environ['OPENSKY_TRINO_PASSWORD'] = 'your_trino_password' # For S3 access os.environ['OPENSKY_ACCESS_KEY'] = 'your_s3_access_key' os.environ['OPENSKY_SECRET_KEY'] = 'your_s3_secret_key' ``` -------------------------------- ### Access OpenSky Network Data via Trino Database (Python) Source: https://github.com/open-aviation/pyopensky/blob/master/readme.md Shows how to connect to and query the OpenSky Network's historical data using the pyopensky.trino module and the Trino database. Requires authentication and provides methods for flight lists, history, and raw data. ```python from pyopensky.trino import Trino trino = Trino() # full description of the whole set of parameters in the documentation trino.flightlist(start, stop, *, airport, callsign, icao24) trino.history(start, stop, *, callsign, icao24, bounds) trino.rawdata(start, stop, *, callsign, icao24, bounds) ``` -------------------------------- ### Batch Processing with Delays for API Requests - Python Source: https://context7.com/open-aviation/pyopensky/llms.txt This code snippet demonstrates a pattern for batch processing requests to the REST API, specifically fetching departure data for multiple airports. It includes a `time.sleep(1)` call within the loop to introduce a delay between requests, which is a good practice to avoid hitting rate limits and be considerate of the API's resources. ```python from pyopensky.rest import REST import pandas as pd import logging import time logging.basicConfig(level=logging.INFO) rest = REST() airports = ["LFPG", "EGLL", "EDDF", "EHAM"] start = pd.Timestamp("2024-01-15", tz="utc") stop = start + pd.Timedelta("1d") all_flights = [] for airport in airports: try: flights = rest.departure(airport, start, stop) all_flights.append(flights) time.sleep(1) # Be nice to the API except Exception as e: logging.error(f"Failed to fetch {airport}: {e}") continue if all_flights: combined = pd.concat(all_flights, ignore_index=True) ``` -------------------------------- ### List OpenSky S3 Objects for a Specific Hour Source: https://context7.com/open-aviation/pyopensky/llms.txt List available data files in the OpenSky S3 storage for a given hour and table type (e.g., 'state_vectors'). This is a precursor to downloading specific files. ```python objects = list(s3.list_objects( hour=hour, table="state_vectors", folder="tables_v4" )) ``` -------------------------------- ### REST API Rate Limiting and Retries - Python Source: https://context7.com/open-aviation/pyopensky/llms.txt Illustrates how the REST client automatically handles rate limiting and common API errors. It includes setting up logging to observe warnings and demonstrates a try-except block for fetching states, showing that the client retries on 503 errors and waits on 429 (rate limit) errors. ```python from pyopensky.rest import REST import pandas as pd import logging # Enable logging to see rate limit warnings logging.basicConfig(level=logging.INFO) rest = REST() trino = Trino() # REST API automatically handles rate limiting try: states = rest.states() # API automatically: # - Retries on 503 errors (up to 5 times) # - Waits and retries on 429 (rate limit) errors # - Warns when rate limit is low (< 100 requests remaining) except Exception as e: print(f"Error fetching states: {e}") ``` -------------------------------- ### Download OpenSky S3 File to Disk Source: https://context7.com/open-aviation/pyopensky/llms.txt Download a specific data file from OpenSky S3 storage to a local directory. The downloaded file can then be read into a pandas DataFrame. ```python output_dir = Path("./data") output_dir.mkdir(exist_ok=True) downloaded_file = s3.download_object(obj, filename=output_dir) ``` -------------------------------- ### Access OpenSky Network Data via REST API (Python) Source: https://github.com/open-aviation/pyopensky/blob/master/readme.md Demonstrates how to use the pyopensky.rest module to fetch various types of flight data from the OpenSky Network REST API. Requires instantiation of the REST class. ```python from pyopensky.rest import REST rest = REST() rest.states() rest.tracks(icao24) rest.routes(callsign) rest.aircraft(icao24, begin, end) rest.arrival(airport, begin, end) rest.departure(airport, begin, end) ``` -------------------------------- ### Download OpenSky S3 File to Memory Buffer Source: https://context7.com/open-aviation/pyopensky/llms.txt Download a data file from OpenSky S3 storage directly into a memory buffer, allowing for immediate processing without writing to disk. This is useful for smaller datasets or streaming scenarios. ```python buffer = s3.download_object(objects[0], filename=None, return_buffer=True) ``` -------------------------------- ### Query Airport Trajectories with Time Buffer (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve trajectory data for flights departing from a specific airport, including a time buffer before and after the flight times. A limit can be set for the number of results. ```python airport_trajectories = trino.history( start, stop, departure_airport="LFPG", time_buffer="30min", # Include data 30min before/after flight times limit=10 ) ``` -------------------------------- ### List Raw ADS-B Messages in OpenSky S3 Source: https://context7.com/open-aviation/pyopensky/llms.txt List available raw ADS-B message files from OpenSky S3 storage for a specific hour. These files are typically stored under the 'raw' folder. ```python raw_objects = list(s3.list_objects( hour=hour, table="ads-b.mode-s-v2", folder="raw" )) ``` -------------------------------- ### Query Flights by Specific Aircraft (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Query the Trino database for flights associated with specific aircraft, identified by their ICAO24 address. A limit can be applied to the number of results returned. ```python aircraft_flights = trino.flightlist( start, stop, icao24=["a12345", "a12346"], # Multiple aircraft limit=100 ) ``` -------------------------------- ### Query Trajectories within Geographic Bounds (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve trajectory data for flights within a specified geographic bounding box (west, south, east, north). Options include caching and compressing cache files. ```python bounds_switzerland = (5.96, 45.82, 10.49, 47.81) # west, south, east, north swiss_traffic = trino.history( start, stop, bounds=bounds_switzerland, cached=True, compress=True # Compress cache files to save space ) ``` -------------------------------- ### Joining Trajectory Data with Flight Metadata - Python Source: https://context7.com/open-aviation/pyopensky/llms.txt This snippet shows how to retrieve flight trajectories after performing a flight list query. It iterates through the results of a flight list query, fetches the history for each flight, and then concatenates all trajectories into a single pandas DataFrame for further analysis. ```python if flights is not None: trajectories = [] for idx, flight in flights.head(5).iterrows(): traj = trino.history( flight['firstseen'], flight['lastseen'], icao24=flight['icao24'], callsign=flight['callsign'], cached=True ) if traj is not None: trajectories.append(traj) # Combine all trajectories if trajectories: all_traj = pd.concat(trajectories, ignore_index=True) print(f"Total positions: {len(all_traj)}") ``` -------------------------------- ### Filter Flights by Callsign and Departure Airport (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve flight lists from the Trino database, filtering by a callsign with a wildcard and a specific departure airport. This is useful for isolating flights of a particular airline. ```python air_france = trino.flightlist( start, stop, callsign="AFR%", # All Air France flights departure_airport="LFPG" ) ``` -------------------------------- ### Filter Trajectories by Sensor IDs (Trino) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieve trajectory data filtered by specific OpenSky sensor IDs (serials) and a particular aircraft's ICAO24 address. This allows for highly specific data retrieval. ```python sensor_data = trino.history( start, stop, serials=[1234, 5678], # Specific OpenSky sensor IDs icao24="a12345" ) ``` -------------------------------- ### Retrieve Aircraft Trajectory Waypoints (REST API) Source: https://context7.com/open-aviation/pyopensky/llms.txt Retrieves historical trajectory waypoints for a specific aircraft identified by its ICAO24 address at a given timestamp. This function is useful for analyzing an aircraft's past movement patterns. It requires the aircraft's ICAO24 address and a pandas Timestamp object. Returns a pandas DataFrame with waypoint data. ```python from pyopensky.rest import REST import pandas as pd rest = REST() # Get track for specific aircraft at a given time icao24 = "a12345" timestamp = pd.Timestamp("2024-01-15 12:00:00", tz="utc") track = rest.tracks(icao24, ts=timestamp) # Returns DataFrame with columns: timestamp, latitude, longitude, # altitude, track, onground, icao24, callsign print(f"Retrieved {len(track)} waypoints") for idx, row in track.iterrows(): print(f"{row['timestamp']}: ({row['latitude']}, {row['longitude']}) " f"alt={row['altitude']}m, onground={row['onground']}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.