### Install Spacetrack using pip Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/installation.md Use this command to install the spacetrack library from PyPI. This is the recommended method for most users. ```bash pip install spacetrack ``` -------------------------------- ### Install spacetrack via pip Source: https://github.com/python-astrodynamics/spacetrack/blob/master/README.rst Use this command to install the module in your environment. ```bash $ pip install spacetrack ``` -------------------------------- ### Interact with Space-Track API Source: https://github.com/python-astrodynamics/spacetrack/blob/master/README.rst Examples covering client initialization, data retrieval, streaming, and connection management. ```python >>> from spacetrack import SpaceTrackClient >>> st = SpaceTrackClient('identity', 'password') >>> print(st.gp(norad_cat_id=[25544, 41335], format='tle')) 1 25544U 98067A 16179.00000000 .00000000 00000-0 00000-0 0 0000 2 25544 00.0000 0.0000 0000000 00.0000 000.0000 00.00000000 0000 1 41335U 16011A 16179.00000000 .00000000 00000-0 00000-0 0 0000 2 41335 00.0000 0.0000 0000000 00.0000 000.0000 00.00000000 0000 >>> # Operators, to save manual string formatting. >>> import spacetrack.operators as op >>> from datetime import datetime >>> drange = op.inclusive_range(datetime(2016, 6, 26), datetime(2016, 6, 27)) >>> # Streaming downloads line by line >>> lines = st.gp_history(iter_lines=True, creation_date=drange, orderby='TLE_LINE1', format='tle') >>> with open('tle.txt', 'w') as fp: ... for line in lines: ... fp.write(line) >>> # Streaming downloads in chunk (note file is opened in binary mode) >>> content = st.download(iter_content=True, file_id=..., format='stream') >>> with open('file.txt', 'wb') as fp: ... for chunk in content: ... fp.write(chunk) >>> # Parameter checking, using Space-Track's modeldef API >>> st.gp(onrad_cat_id=25544) TypeError: 'gp' got an unexpected argument 'onrad_cat_id' >>> # Automatic rate limiting >>> for satno in my_satnos: ... # Gets limited to <30 requests per minute automatically by blocking ... st.gp(...) >>> # Log out and close connections >>> st.close() ``` -------------------------------- ### Starts With Operator Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md Formats a value for a prefix matching query predicate. ```python '^value' ``` -------------------------------- ### Asynchronous Streaming Download Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Example of performing an asynchronous download of TLE data using `AsyncSpaceTrackClient`. It streams lines to a file and requires an asyncio event loop. ```python import asyncio import spacetrack.operators as op from spacetrack.aio import AsyncSpaceTrackClient async def download_latest_tles(): async with AsyncSpaceTrackClient( identity="user@example.com", password="password" ) as st: data = await st.gp( iter_lines=True, epoch=">now-30", mean_motion=op.inclusive_range(0.99, 1.01), eccentricity=op.less_than(0.01), format="tle", ) with open("tle_latest.txt", "w") as fp: async for line in data: fp.write(line + "\n") loop = asyncio.get_event_loop() loop.run_until_complete(download_latest_tles()) ``` -------------------------------- ### Clone Spacetrack Repository from Git Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/installation.md Clone the spacetrack repository from GitHub to install from source. This is useful for development or if you need a specific version. ```bash git clone https://github.com/python-astrodynamics/spacetrack.git Cloning into 'spacetrack'... ``` -------------------------------- ### Synchronous Streaming Download Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Example of performing a synchronous download of TLE data, streaming lines to a file. It uses operators for filtering and specifies the output format. ```python import spacetrack.operators as op from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: data = st.gp( iter_lines=True, epoch=">now-30", mean_motion=op.inclusive_range(0.99, 1.01), eccentricity=op.less_than(0.01), format="tle", ) with open("tle_latest.txt", "w") as fp: for line in data: fp.write(line + "\n") ``` -------------------------------- ### Get Predicates for a Request Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Shows how to retrieve valid predicates for a specific request class, such as `gp_history`, using different methods on the SpaceTrackClient. ```python st.gp_history.get_predicates() st.gp_history.get_predicates(controller="basicspacedata") st.basicspacedata.gp_history.get_predicates() st.basicspacedata.get_predicates("gp_history") st.get_predicates("gp_history") st.get_predicates("gp_history", controller="basicspacedata") ``` -------------------------------- ### Get GP History in XML Format Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Fetch the General Perturbations (GP) history for NORAD catalog ID 25544, ordered by epoch descending, with a limit of 22. Results are returned in XML format. ```python st.gp_history(norad_cat_id=25544, orderby="epoch desc", limit=22, format="xml") ``` -------------------------------- ### Get Boxscore Data in CSV Format Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve the boxscore data from Space-Track in CSV format. This is a simple query to get a summary of available data. ```python output = st.boxscore(format="csv") ``` -------------------------------- ### Get Predicates Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Method to retrieve predicate information for a given request class. ```APIDOC ## Get Predicates ### get_predicates(class_, controller=None) #### Description Retrieves full predicate information for a specified request class and caches it for future calls. #### Method `async` #### Parameters: - **class_** (str) - Required - The Space-Track request class name. - **controller** (str) - Optional - The request controller to use. ``` -------------------------------- ### Get GP History in TLE Format Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve the General Perturbations (GP) history for a specific NORAD catalog ID (25544), ordered by epoch in descending order, with a limit of 22 results. Results are formatted as TLE. ```python st.gp_history(norad_cat_id=25544, orderby="epoch desc", limit=22, format="tle") ``` -------------------------------- ### AsyncSpaceTrackClient Initialization Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Information on how to initialize the asynchronous Space-Track client. ```APIDOC ## AsyncSpaceTrackClient Initialization ### Description Initializes an asynchronous client for the Space-Track API. This client can be used as an async context manager or by manually calling `close()`. ### Parameters - **identity** (str) - Required - Your Space-Track username. - **password** (str) - Required - Your Space-Track password. - **base_url** (str) - Optional - The base URL for the Space-Track API. Defaults to 'https://www.space-track.org/'. - **rush_store** (any) - Optional - For rush requests. - **rush_key_prefix** (str) - Optional - Prefix for rush keys. - **httpx_client** (httpx.AsyncClient) - Optional - An existing `httpx.AsyncClient` instance. - **additional_rate_limit** (int) - Optional - Additional rate limit to apply. - **cache_path** (str) - Optional - Path to a cache directory. ``` -------------------------------- ### SpaceTrackClient Initialization and Authentication Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Demonstrates how to initialize the SpaceTrackClient and covers authentication and logout procedures. ```APIDOC ## SpaceTrackClient Class ### Description Provides a client for interacting with the Space-Track API. ### Parameters - **identity** (string) - Required - Space-Track username. - **password** (string) - Required - Space-Track password. - **base_url** (string) - Optional - Base URL for the Space-Track API. Defaults to 'https://www.space-track.org/'. - **rush_store** (object) - Optional - A `rush` storage backend for rate limiting. - **rush_key_prefix** (string) - Optional - Prefix for keys stored in `rush_store`. - **httpx_client** (object) - Optional - A custom `httpx.Client` instance. - **additional_rate_limit** (object) - Optional - An additional `rush.quota.Quota` for rate limiting. - **cache_path** (string) - Optional - Directory for caching. ### Methods #### authenticate() - **Description**: Authenticates with Space-Track. - **Raises**: - `spacetrack.base.AuthenticationError` – Incorrect login details. - **Note**: This method is called automatically when required. #### logout() - **Description**: Logs out of Space-Track. - **Note**: This method is called automatically when using `SpaceTrackClient` as a context manager or when `close()` is used. ``` -------------------------------- ### Initialize and Use SpaceTrackClient Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Initialize the SpaceTrackClient with credentials and perform various queries. The client manages authentication and rate limiting. Use a 'with' statement for proper session management. ```python from spacetrack import SpaceTrackClient # Initialize client with credentials with SpaceTrackClient(identity="user@example.com", password="password") as st: # Query GP (General Perturbations) data for specific satellites # Returns parsed JSON by default iss_data = st.gp(norad_cat_id=25544) print(f"ISS orbital data: {iss_data}") # Query multiple satellites at once satellites = st.gp(norad_cat_id=[25544, 41335]) for sat in satellites: print(f"NORAD ID: {sat['NORAD_CAT_ID']}, Name: {sat['OBJECT_NAME']}") # Get TLE format output tle_data = st.gp(norad_cat_id=25544, format="tle") print(tle_data) # Output: # 1 25544U 98067A 24001.00000000 .00000000 00000-0 00000-0 0 0000 # 2 25544 51.6400 000.0000 0001234 00.0000 000.0000 15.50000000000000 # Query satellite catalog satcat = st.satcat(norad_cat_id=25544) print(f"Launch date: {satcat[0]['LAUNCH']}") # Get decay predictions decays = st.decay(limit=10, orderby="decay_epoch desc") for decay in decays: print(f"Object: {decay['OBJECT_NAME']}, Decay: {decay['DECAY_EPOCH']}") ``` -------------------------------- ### Initialize SpaceTrackClient Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Instantiate the SpaceTrackClient with user credentials. This client is used for all subsequent interactions with the Spacetrack API. ```python import spacetrack.operators as op from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: ... ``` -------------------------------- ### Using SpaceTrackClient as a Context Manager Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Demonstrates the recommended way to use the SpaceTrackClient to ensure automatic logout. The client handles authentication and logout implicitly when used within a 'with' statement. ```python with SpaceTrackClient(...) as client: ... ``` -------------------------------- ### Manage AsyncSpaceTrackClient Lifecycle Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Demonstrates how to handle client closure using an asynchronous context manager or explicit close calls. ```python async with AsyncSpaceTrackClient(...) as client: ... ``` ```python client = AsyncSpaceTrackClient(...) await client.close() ``` -------------------------------- ### Make Requests with SpaceTrackClient Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Demonstrates various equivalent ways to call request classes like `gp_history` on the SpaceTrackClient, including specifying controllers explicitly or implicitly. ```python st.gp_history() st.gp_history(controller="basicspacedata") st.basicspacedata.gp_history() st.generic_request("gp_history") st.generic_request("gp_history", controller="basicspacedata") ``` -------------------------------- ### Checkout a Specific Release Tag Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/installation.md After cloning the repository, navigate into the directory and checkout a specific release tag to use a particular version of the library. ```bash cd spacetrack git checkout 1.4.0 ``` -------------------------------- ### File Upload Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Demonstrates how to upload a file using the `SpaceTrackClient` by passing an opened file object to the `upload` method. ```python from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: with open("somefile.txt", "rb") as fp: st.upload(file=fp) ``` -------------------------------- ### Retrieve Request Predicates Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Shows how to check valid keywords for requests by retrieving predicate information. ```python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') ``` -------------------------------- ### Configure Distributed Rate Limiting with Redis Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Share rate limit state across multiple processes by providing a Redis store instance. ```python from spacetrack import SpaceTrackClient from rush.stores.redis import RedisStore # Create Redis store for distributed rate limiting redis_store = RedisStore(url="redis://localhost:6379/0") with SpaceTrackClient( identity="user@example.com", password="password", rush_store=redis_store, rush_key_prefix="myapp_" # Avoid key conflicts ) as st: # Rate limits now shared across all instances using this Redis data = st.gp(norad_cat_id=25544) ``` -------------------------------- ### Execute Common Space-Track Queries Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Demonstrates various queries including boxscore statistics, recent launches, decay predictions, high LEO satellites, TLE history, TIP messages, and conjunction data messages. Uses the `spacetrack.operators` module for complex query conditions. ```python import spacetrack.operators as op from spacetrack import SpaceTrackClient from datetime import date with SpaceTrackClient(identity="user@example.com", password="password") as st: # Get boxscore statistics boxscore = st.boxscore(format="csv") # Recent satellite launches (last 7 days) recent_launches = st.satcat( launch=">now-7", current="Y", orderby="launch desc", format="html" ) # Decay predictions for specific date range decay_range = op.inclusive_range(date(2024, 7, 1), date(2024, 7, 31)) decays = st.decay( decay_epoch=decay_range, orderby=["norad_cat_id", "precedence"], format="xml" ) # High LEO satellites (high mean motion) high_leo = st.gp( epoch=">now-30", mean_motion=op.greater_than(11.25), format="3le" ) # ISS TLE history (last 22 entries) iss_history = st.gp_history( norad_cat_id=25544, orderby="epoch desc", limit=22, format="tle" ) # Tracking and Impact Prediction messages tip_data = st.tip( norad_cat_id=[60, 38462, 38351], format="html" ) # Conjunction Data Messages for Iridium constellation iridium_cdm = st.cdm( constellation="iridium", limit=10, orderby="creation_date desc", format="kvn" ) # Future conjunctions with specific predicates future_cdm = st.cdm( constellation="intelsat", tca=">now", # Time of closest approach in future predicates=["message_for", "tca", "miss_distance"], orderby="miss_distance", format="html", metadata=True ) ``` -------------------------------- ### Accessing Request Classes via SpaceTrackClient Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Demonstrates different ways to access request classes, including automatic controller resolution and explicit specification. Lists available request classes per controller. ```python from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: # These are equivalent - controller is auto-resolved data1 = st.gp(norad_cat_id=25544) data2 = st.basicspacedata.gp(norad_cat_id=25544) data3 = st.generic_request("gp", norad_cat_id=25544) data4 = st.generic_request("gp", controller="basicspacedata", norad_cat_id=25544) # Available request classes by controller: # basicspacedata: gp, gp_history, satcat, satcat_change, satcat_debut, # decay, tip, boxscore, announcement, cdm_public, launch_site # expandedspacedata: cdm, car, maneuver, maneuver_history, organization, satellite # fileshare: file, folder, upload, download, delete # spephemeris: file, file_history, download # publicfiles: dirs, download # Query conjunction data messages (expanded space data) cdm_data = st.cdm(constellation="iridium", limit=5, orderby="creation_date desc") # Query satellite catalog changes changes = st.satcat_change(limit=10) # Get boxscore statistics boxscore = st.boxscore(format="csv") ``` -------------------------------- ### Use SpaceTrackClient as a Context Manager Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/changelog.md It is recommended to use SpaceTrackClient as a context manager for explicit session logout. This ensures proper cleanup of resources. ```python with SpaceTrackClient(...) as st: st.gp(...) ``` -------------------------------- ### Query CDM Data for Intelsat with Predicates in KVN Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Fetch Collision Detection and Avoidance (CDM) data for the 'intelsat' constellation, filtered for events after the current time. It includes specific predicates and orders results by miss distance. The output is in KVN format. ```python st.cdm( constellation="intelsat", tca=">now", predicates=["message_for", "tca", "miss_distance"], orderby="miss_distance", format="kvn", ) ``` -------------------------------- ### Query CDM Data for Intelsat with Predicates in HTML Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve Collision Detection and Avoidance (CDM) data for the 'intelsat' constellation, filtered for events occurring after the current time ('tca=">now"'). Includes specific predicates and orders by miss distance. Results are in HTML format and include metadata. ```python st.cdm( constellation="intelsat", tca=">now", predicates=["message_for", "tca", "miss_distance"], orderby="miss_distance", format="html", metadata=True, ) ``` -------------------------------- ### Query GP Data by Epoch, Mean Motion, and Eccentricity Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Fetch General Perturbations (GP) data for satellites launched within the last 30 days, with a mean motion between 0.99 and 1.01, and eccentricity less than 0.01. Results are formatted as TLE. ```python st.gp( epoch=">now-30", mean_motion=op.inclusive_range(0.99, 1.01), eccentricity=op.less_than(0.01), format="tle", ) ``` -------------------------------- ### Upload Files to Space-Track Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Upload local files using the SpaceTrackClient upload method. ```python from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: # Upload a file to Space-Track with open("observations.txt", "rb") as fp: result = st.upload(file=fp, folder_id=123) print(f"Upload result: {result}") ``` -------------------------------- ### Perform Asynchronous Space-Track Queries Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Use AsyncSpaceTrackClient for non-blocking requests. Supports streaming downloads and asynchronous iteration over results. ```python import asyncio import spacetrack.operators as op from spacetrack.aio import AsyncSpaceTrackClient async def download_latest_tles(): async with AsyncSpaceTrackClient( identity="user@example.com", password="password" ) as st: # Regular async query iss_data = await st.gp(norad_cat_id=25544) print(f"ISS data: {iss_data}") # Async streaming downloads data = await st.gp( iter_lines=True, epoch=">now-30", mean_motion=op.inclusive_range(0.99, 1.01), eccentricity=op.less_than(0.01), format="tle" ) with open("tle_latest.txt", "w") as fp: async for line in data: fp.write(line + "\n") # Query satellite catalog asynchronously satellites = await st.satcat( launch=">now-7", current="Y", orderby="launch desc" ) # Get predicates asynchronously predicates = await st.get_predicates("gp") return satellites # Run the async function satellites = asyncio.run(download_latest_tles()) ``` -------------------------------- ### Manage Rate Limiting and Callbacks Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Register a callback to handle rate limit events or configure stricter limits using the additional_rate_limit parameter. ```python import time from spacetrack import SpaceTrackClient from rush.quota import Quota def rate_limit_callback(until): """Called when rate limit is hit""" duration = int(round(until - time.monotonic())) print(f"Rate limit reached. Sleeping for {duration} seconds.") with SpaceTrackClient(identity="user@example.com", password="password") as st: # Set callback to be notified of rate limiting st.callback = rate_limit_callback # Make many requests - rate limiting handled automatically norad_ids = range(25544, 25600) for norad_id in norad_ids: try: data = st.gp(norad_cat_id=norad_id) if data: print(f"Got data for {norad_id}") except Exception as e: print(f"Error for {norad_id}: {e}") # For stricter rate limiting, use additional_rate_limit with SpaceTrackClient( identity="user@example.com", password="password", additional_rate_limit=Quota.per_minute(10) # Only 10 req/min ) as st: data = st.gp(norad_cat_id=25544) ``` -------------------------------- ### Query TIP Data by NORAD Catalog ID Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve TIP (Two-Line Element Set) data for a list of NORAD catalog IDs. Results are formatted as HTML. ```python st.tip(norad_cat_id=[60, 38462, 38351], format="html") ``` -------------------------------- ### Query GP Data by Epoch and Mean Motion Greater Than Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve General Perturbations (GP) data for satellites launched within the last 30 days, with a mean motion greater than 11.25. Results are formatted as 3LE. ```python st.gp( epoch=">now-30", mean_motion=op.greater_than(11.25), format="3le" ) ``` -------------------------------- ### Discover Query Predicates Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Retrieve valid predicate fields for request classes to understand available filtering parameters. ```python from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: # Get predicates for GP request class predicates = st.get_predicates("gp") # Or equivalently: predicates = st.gp.get_predicates() predicates = st.basicspacedata.gp.get_predicates() # Print available predicates for pred in predicates: print(f"Name: {pred.name}, Type: {pred.type_}, Nullable: {pred.nullable}") # Output: # Name: ccsds_omm_vers, Type: str, Nullable: True # Name: comment, Type: str, Nullable: True # Name: creation_date, Type: datetime, Nullable: True # Name: originator, Type: str, Nullable: True # Name: norad_cat_id, Type: int, Nullable: False # Name: object_name, Type: str, Nullable: True # Name: object_id, Type: str, Nullable: True # Name: epoch, Type: datetime, Nullable: True # Name: mean_motion, Type: float, Nullable: True # Name: eccentricity, Type: float, Nullable: True # Name: inclination, Type: float, Nullable: True # ... and many more # Get predicates for satellite catalog satcat_predicates = st.get_predicates("satcat") # Get predicates with explicit controller cdm_predicates = st.get_predicates("cdm", controller="expandedspacedata") ``` -------------------------------- ### Query Satcat Data for Recent Launches Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve satellite catalog data for satellites launched within the last 7 days, currently active, and ordered by launch date in descending order. Returns data in HTML format. ```python st.satcat(launch=">now-7", current="Y", orderby="launch desc", format="html") ``` -------------------------------- ### Async Authentication and Logout Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Methods for handling authentication and logging out of the Space-Track API asynchronously. ```APIDOC ## Async Authentication and Logout ### authenticate() #### Description Authenticates with the Space-Track API. This method is called automatically when needed. #### Method `async` #### Raises: - **spacetrack.base.AuthenticationError** – Incorrect login details. ### logout() #### Description Logs out of the Space-Track API. This is called automatically when the client is used as an async context manager or when `close()` is invoked. #### Method `async` ``` -------------------------------- ### Query CDM Data for Iridium Constellation in KVN Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Fetch Collision Detection and Avoidance (CDM) data for the 'iridium' constellation, limited to 10 entries, sorted by creation date in descending order. Results are in KVN format. ```python st.cdm(constellation="iridium", limit=10, orderby="creation_date desc", format="kvn") ``` -------------------------------- ### Generic Request Method Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Details on how to perform generic requests to the Space-Track API. ```APIDOC ## Generic Request Method ### generic_request(class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, timeout=, **kwargs) #### Description Performs a generic query to the Space-Track API. This method is used internally by specific API endpoint methods. #### Method `async` #### Parameters: - **class_** (str) - Required - The Space-Track request class name (e.g., 'tle_publish'). - **iter_lines** (bool) - Optional - If True, yields result line by line. - **iter_content** (bool) - Optional - If True, yields result in 100 KiB chunks. - **controller** (str) - Optional - Specifies the request controller to use (e.g., 'basicspacedata'). - **parse_types** (bool) - Optional - If True, parses string values in the response according to type information. - **timeout** (httpx.Timeout) - Optional - Timeout for the request. - **kwargs** - Arbitrary keyword arguments that must match the predicate fields on Space-Track. #### Yields: - Lines (str) - Stripped of newline characters, if `iter_lines=True`. - Chunks (bytes) - 100 KiB chunks, if `iter_content=True`. #### Returns: - dict - Parsed JSON object, unless `format='json'` is passed in kwargs, in which case the JSON is returned unparsed. #### WARNING Do not set `format='json'` if you want the parsed JSON object returned. ``` -------------------------------- ### AsyncSpaceTrackClient Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/module.md The asynchronous client for non-blocking interactions with the Space-Track API. ```APIDOC ## Class: AsyncSpaceTrackClient ### Description Asynchronous client class for performing non-blocking requests to the Space-Track API using asyncio. ``` -------------------------------- ### Query GP Data by NORAD Catalog ID Range and Pattern Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Fetch General Perturbations (GP) data for a specific set of NORAD catalog IDs, including a range, a pattern match, and a prefix match. Results are ordered by NORAD catalog ID and formatted as HTML. ```python st.gp( norad_cat_id=[ 36000, op.inclusive_range(36001, 36004), op.like(36005), op.startswith(3600), 36010, ], orderby="norad_cat_id", format="html", ) ``` -------------------------------- ### Query CDM Data for Iridium Constellation in HTML Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve Collision Detection and Avoidance (CDM) data for the 'iridium' constellation, limited to 10 results, ordered by creation date descending. Results are formatted as HTML. ```python st.cdm(constellation="iridium", limit=10, orderby="creation_date desc", format="html") ``` -------------------------------- ### Generic Request API Mapping Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Illustrates the mapping between public API methods and their underlying generic_request calls. ```python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) ``` ```python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) ``` -------------------------------- ### Explicitly Closing SpaceTrackClient Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Shows how to manually close the SpaceTrackClient when not using it as a context manager. This is necessary to release resources and log out properly. ```python client = SpaceTrackClient(...) client.close() ``` -------------------------------- ### generic_request Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Executes a generic Space-Track query based on the specified request class and controller. ```APIDOC ## generic_request ### Description Performs a generic request to the Space-Track API. This method is used internally by specific request methods but can be called directly. ### Parameters - **class_** (str) - Required - Space-Track request class name. - **iter_lines** (bool) - Optional - Yield result line by line. - **iter_content** (bool) - Optional - Yield result in 100 KiB chunks. - **controller** (str) - Optional - Specify request controller to use. - **parse_types** (bool) - Optional - Parse string values in response according to predicate information. - **timeout** (object) - Optional - Override default client timeout. - **kwargs** (dict) - Optional - Predicate fields for the Space-Track query. ### Returns - Parsed JSON object (unless format keyword is passed). ``` -------------------------------- ### Set Custom Rate Limit Callback Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Register a custom callback function to be executed when the rate limit is about to be hit. The callback receives the remaining time until the limit is reset. ```python import time from spacetrack import SpaceTrackClient def mycallback(until): duration = int(round(until - time.monotonic())) print("Sleeping for {:d} seconds.".format(duration)) with SpaceTrackClient(identity="user@example.com", password="password") as st: st.callback = mycallback ``` -------------------------------- ### Like Operator Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md Formats a value for a pattern matching query predicate. ```python '~~value' ``` -------------------------------- ### SpaceTrack Operators Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/module.md Utility functions for building query predicates. ```APIDOC ## Operators ### Description Functions used to define filtering logic for API queries. ### Available Operators - **greater_than()** - **less_than()** - **not_equal()** - **inclusive_range()** - **like()** - **startswith()** ``` -------------------------------- ### Query Decay Data by Date Range Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Fetch decay data for a specified date range, ordered by NORAD catalog ID and precedence. Requires the 'op' and 'date' modules. ```python decay_epoch = op.inclusive_range(date(2012, 7, 2), date(2012, 7, 9)) st.decay(decay_epoch=decay_epoch, orderby=["norad_cat_id", "precedence"], format="xml") ``` -------------------------------- ### Value Stringification Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md Utility for converting Python objects into Space-Track compatible string formats. ```APIDOC ## Stringify Predicate Value ### Description Converts Python objects (booleans, sequences, dates, None) into strings suitable for Space-Track API predicates. ### Method `_stringify_predicate_value(value)` ### Endpoint N/A (Internal utility function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from spacetrack.operators import _stringify_predicate_value print(_stringify_predicate_value(True)) # Output: 'true' print(_stringify_predicate_value([25544, 34602])) # Output: '25544,34602' print(_stringify_predicate_value(None)) # Output: 'null-val' ``` ### Response N/A ``` -------------------------------- ### SpaceTrackClient Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/module.md The primary client for interacting with the Space-Track API synchronously. ```APIDOC ## Class: SpaceTrackClient ### Description Main client class for performing synchronous requests to the Space-Track API. ### Methods - **__init__(identity, password)** - Initializes the client with credentials. - **query(...)** - Executes a query against the Space-Track database. ``` -------------------------------- ### Query Satcat Data with Period Less Than Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Retrieve satellite catalog data for currently active satellites with an orbital period less than 128. Decay is not specified, and results are ordered by NORAD catalog ID. ```python st.satcat(period=op.less_than(128), decay=None, current="Y") ``` -------------------------------- ### Less Than Operator Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md Formats a value for a less-than query predicate. ```python ' 1400 minutes (high orbit) high_orbit = st.satcat( period=op.greater_than(1400), current="Y", decay=None ) # less_than: Find LEO satellites with period < 128 minutes leo_satellites = st.satcat( period=op.less_than(128), decay=None, current="Y" ) # inclusive_range: Query date range date_range = op.inclusive_range(date(2024, 1, 1), date(2024, 1, 31)) recent_decays = st.decay(decay_epoch=date_range) # inclusive_range: Query orbital period range (GEO satellites ~1436 min) geo_satellites = st.satcat( period=op.inclusive_range(1430, 1450), current="Y", decay=None ) # like: Pattern matching with wildcards starlink = st.satcat(object_name=op.like("STARLINK%")) # startswith: Find NORAD IDs starting with 3600 matching_ids = st.gp(norad_cat_id=op.startswith(3600)) # not_equal: Exclude specific values non_debris = st.satcat(object_type=op.not_equal("DEBRIS")) # Combine multiple NORAD IDs with operators complex_query = st.gp( norad_cat_id=[ 36000, op.inclusive_range(36001, 36004), op.like(36005), op.startswith(3600), 36010, ], orderby="norad_cat_id", format="html" ) # Query recent TLEs with specific orbital characteristics recent_tles = st.gp( epoch=">now-30", # Last 30 days mean_motion=op.inclusive_range(0.99, 1.01), # Near GEO eccentricity=op.less_than(0.01), # Near circular format="tle" ) ``` -------------------------------- ### Request Controllers Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Information about the available request controllers within the SpaceTrackClient. ```APIDOC ## Request Controllers ### Description An ordered dictionary of request controllers and their associated request classes. ### Available Controllers - basicspacedata - expandedspacedata - fileshare - spephemeris ### Usage Note If a method is called without specifying a controller, the client defaults to the first controller in the order (e.g., `fileshare` before `spephemeris`). To add support for new controllers not yet included in the library, subclass `SpaceTrackClient` and override the `request_controllers` attribute. ``` -------------------------------- ### String Matching Operators Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md These operators are used for string pattern matching in Space-Track queries. ```APIDOC ## Like Operator ### Description Represents the 'like' operator for wildcard matching in Space-Track queries. ### Method `like(value)` ### Endpoint N/A (Operator definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from spacetrack.operators import like query = f"LIKE {like('%satellite%')}" ``` ### Response N/A ``` ```APIDOC ## Starts With Operator ### Description Represents the 'starts with' operator for string matching in Space-Track queries. ### Method `startswith(value)` ### Endpoint N/A (Operator definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from spacetrack.operators import startswith query = f"SW {startswith('ISS')}" ``` ### Response N/A ``` -------------------------------- ### Predicate Object Structure Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Illustrates the structure of a `Predicate` object returned by `get_predicates()`, showing its name, type, nullability, and default value. ```python [ Predicate(name='creation_date', type_='datetime', nullable=True, default=None), Predicate(name='object_name', type_='str', nullable=True, default=None), Predicate(name='eccentricity', type_='float', nullable=True, default=None), ... # and many more ] ``` -------------------------------- ### close Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Closes the connection to the Space-Track API. ```APIDOC ## close ### Description Logs out of Space-Track if necessary and closes any open connections. ``` -------------------------------- ### Comparison Operators Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md These operators are used for comparing values in Space-Track queries. ```APIDOC ## Greater Than Operator ### Description Represents the greater than operator for Space-Track queries. ### Method `greater_than(value)` ### Endpoint N/A (Operator definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from spacetrack.operators import greater_than query = f"GE {greater_than(10)}" ``` ### Response N/A ``` ```APIDOC ## Less Than Operator ### Description Represents the less than operator for Space-Track queries. ### Method `less_than(value)` ### Endpoint N/A (Operator definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from spacetrack.operators import less_than query = f"LE {less_than(5)}" ``` ### Response N/A ``` ```APIDOC ## Not Equal Operator ### Description Represents the not equal operator for Space-Track queries. ### Method `not_equal(value)` ### Endpoint N/A (Operator definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from spacetrack.operators import not_equal query = f"NE {not_equal('active')}" ``` ### Response N/A ``` ```APIDOC ## Inclusive Range Operator ### Description Represents an inclusive range operator for Space-Track queries. ### Method `inclusive_range(left, right)` ### Endpoint N/A (Operator definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from spacetrack.operators import inclusive_range query = f"R1 {inclusive_range(100, 200)}" ``` ### Response N/A ``` -------------------------------- ### Stream Large Datasets Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Use iter_lines or iter_content to process large responses efficiently without loading the entire payload into memory. ```python import spacetrack.operators as op from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: # Stream TLE data line by line (text mode) data = st.gp( iter_lines=True, epoch=">now-30", mean_motion=op.inclusive_range(0.99, 1.01), eccentricity=op.less_than(0.01), format="tle" ) # Write to file efficiently with open("tle_latest.txt", "w") as fp: for line in data: fp.write(line + "\n") # Stream historical TLE data from datetime import date date_range = op.inclusive_range(date(2024, 1, 1), date(2024, 1, 7)) historical_tles = st.gp_history( iter_lines=True, norad_cat_id=25544, creation_date=date_range, orderby="epoch", format="tle" ) with open("iss_history.txt", "w") as fp: for line in historical_tles: fp.write(line + "\n") # Stream binary content in chunks (for downloads) content = st.download(iter_content=True, file_id=12345, format="stream") with open("downloaded_file.bin", "wb") as fp: for chunk in content: fp.write(chunk) ``` -------------------------------- ### Close Client Connection Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/aio.md Method to close the client connection and log out. ```APIDOC ## Close Client Connection ### close() #### Description Logs out of Space-Track and closes any open connections. This method should be called when the client is no longer needed if not using it as an async context manager. #### Method `async` ``` -------------------------------- ### AuthenticationError Exception Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Information about the AuthenticationError exception raised by the SpaceTrack library. ```APIDOC ## AuthenticationError Exception ### Description An exception raised when Space-Track authentication fails due to incorrect login details. ``` -------------------------------- ### Predicate Class Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Details about the Predicate class used for holding Space-Track predicate information. ```APIDOC ## Predicate Class ### Description Holds Space-Track predicate information. ### Parameters - **name** (string) - The name of the predicate. - **type_** (string) - The data type of the predicate. - **nullable** (boolean) - Optional - Whether the predicate can be null. Defaults to `False`. - **default** - Optional - The default value for the predicate. - **values** (list) - Optional - A list of allowed values for the predicate. ``` -------------------------------- ### Not Equal Operator Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md Formats a value for a not-equal query predicate. ```python '<>value' ``` -------------------------------- ### Query Satcat Data by Period Range Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/usage.md Filter satellite catalog data by a specific range of orbital periods (1430 to 1450), for currently active satellites, with no decay, and ordered by NORAD catalog ID. Returns data in HTML format. ```python st.satcat( period=op.inclusive_range(1430, 1450), current="Y", decay=None, orderby="norad_cat_id", format="html", ) ``` -------------------------------- ### get_predicates Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/base.md Retrieves and caches predicate information for a specific request class. ```APIDOC ## get_predicates ### Description Fetches full predicate information for a given request class and caches it for subsequent calls. ### Parameters - **class_** (str) - Required - The request class name. - **controller** (str) - Optional - The request controller. ``` -------------------------------- ### Greater Than Operator Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md Formats a value for a greater-than query predicate. ```python '>value' ``` -------------------------------- ### Inclusive Range Operator Source: https://github.com/python-astrodynamics/spacetrack/blob/master/docs/modules/operators.md Formats a range between two values for a query predicate. ```python 'left--right' ``` -------------------------------- ### Enable Automatic Type Parsing Source: https://context7.com/python-astrodynamics/spacetrack/llms.txt Use parse_types=True to convert API string responses into native Python types. This cannot be used when a specific format parameter is provided. ```python from spacetrack import SpaceTrackClient with SpaceTrackClient(identity="user@example.com", password="password") as st: # Without parse_types - all values are strings data = st.gp(norad_cat_id=25544) print(type(data[0]["EPOCH"])) # print(type(data[0]["MEAN_MOTION"])) # # With parse_types - values converted to Python types data = st.gp(norad_cat_id=25544, parse_types=True) print(type(data[0]["EPOCH"])) # print(type(data[0]["MEAN_MOTION"])) # print(type(data[0]["NORAD_CAT_ID"])) # # Note: parse_types cannot be used with format parameter # This will raise ValueError: # st.gp(norad_cat_id=25544, parse_types=True, format="json") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.