spacetrack documentation¶
spacetrack
is a Python client for Space-Track, with methods for all request
classes, keyword validation for request predicates, streaming download
support, and automatic rate limiting.
Contents:
Installation¶
The recommended installation method is using pip
.
pip¶
$ pip install spacetrack
To install with asyncio
support, install the async extra:
$ pip install spacetrack[async]
Git¶
$ git clone https://github.com/python-astrodynamics/spacetrack.git
Cloning into 'spacetrack'...
Check out a release tag
$ cd spacetrack $ git checkout 0.13.7
Usage¶
import spacetrack.operators as op
from spacetrack import SpaceTrackClient
st = SpaceTrackClient(identity='user@example.com', password='password')
Request classes are presented as methods on the
SpaceTrackClient
object. For example,
st.tle_publish()
. Each request class is part of a request controller.
Since most request classes are only part of one request controller,
spacetrack
looks up the controller for you. It can be specified explicitly
in several ways. All the following are equivalent:
st.tle_publish()
st.tle_publish(controller='basicspacedata')
st.basicspacedata.tle_publish()
st.generic_request('tle_publish')
st.generic_request('tle_publish', controller='basicspacedata')
Request predicates are passed as keyword arguments. Valid
arguments can be checked using the
get_predicates()
method. The following
are equivalent:
st.tle_publish.get_predicates()
st.tle_publish.get_predicates(controller='basicspacedata')
st.basicspacedata.tle_publish.get_predicates()
st.basicspacedata.get_predicates('tle_publish')
st.get_predicates('tle_publish')
st.get_predicates('tle_publish', controller='basicspacedata')
Returned object:
[Predicate(name='publish_epoch', type_='datetime', nullable=False),
Predicate(name='tle_line1', type_='str', nullable=False),
Predicate(name='tle_line2', type_='str', nullable=False)]
Internally, the client uses this mechanism to verify the keyword arguments. Types are not currently checked.
Streaming Downloads¶
It is possible to stream responses by passing iter_content=True
(100 KiB
chunks) or iter_lines=True
to the request class methods.
Example¶
The same example is shown below synchronously and asynchronously.
import spacetrack.operators as op
from spacetrack import SpaceTrackClient
st = SpaceTrackClient(identity='user@example.com', password='password')
data = st.tle_latest(iter_lines=True, ordinal=1, 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')
import asyncio
import spacetrack.operators as op
from spacetrack.aio import AsyncSpaceTrackClient
async def download_latest_tles():
st = AsyncSpaceTrackClient(identity='user@example.com',
password='password')
with st:
data = await st.tle_latest(
iter_lines=True, ordinal=1, 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())
File Uploads¶
To use the upload request class, pass a file keyword argument with the opened file:
from spacetrack import SpaceTrackClient
st = SpaceTrackClient(identity='user@example.com', password='password')
with open('somefile.txt', 'rb') as fp:
st.upload(file=fp)
Rate Limiter¶
“Space-track throttles API use in order to maintain consistent performance for all users. To avoid error messages, please limit your query frequency to less than 20 requests per minute.”
The client will ensure that no more than 19 HTTP requests are sent per minute
by sleeping if the rate exceeds this. This will be logged to the spacetrack
module’s logger. You can register a callback with the
SpaceTrackClient
or
AsyncSpaceTrackClient
classes. It will be passed the
time that the module is sleeping until, in seconds since the epoch (as with
time.time()
).
import time
from spacetrack import SpaceTrackClient
def mycallback(until):
duration = int(round(until - time.time()))
print('Sleeping for {:d} seconds.'.format(duration))
st = SpaceTrackClient(identity='user@example.com', password='password')
st.callback = mycallback
Sample Queries¶
The Space-Track website lists some sample queries, which are shown here using the Python module.
output = st.boxscore(format='csv')
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')
st.satcat(launch='>now-7', current='Y', orderby='launch desc', format='html')
st.satcat(period=op.inclusive_range(1430, 1450), current='Y',
decay=None, orderby='norad_cat_id', format='html')
st.satcat(period=op.less_than(128), decay=None, current='Y')
st.tle_latest(ordinal=1, epoch='>now-30',
mean_motion=op.inclusive_range(0.99, 1.01),
eccentricity=op.less_than(0.01), format='tle')
st.tle_latest(ordinal=1, epoch='>now-30', mean_motion=op.greater_than(11.25),
format='3le')
st.tle_latest(favorites='Amateur', ordinal=1, epoch='>now-30', format='3le')
st.tle_latest(
ordinal=1,
norad_cat_id=[
36000,
op.inclusive_range(36001, 36004),
op.like(36005),
op.startswith(3600),
36010
],
orderby='norad_cat_id',
format='html')
st.tle(norad_cat_id=25544, orderby='epoch desc', limit=22, format='tle')
st.omm(norad_cat_id=25544, orderby='epoch desc', limit=22, format='xml')
st.tip(norad_cat_id=[60, 38462, 38351], format='html')
st.cdm(constellation='iridium', limit=10, orderby='creation_date desc', format='html')
st.cdm(constellation='iridium', limit=10, orderby='creation_date desc', format='kvn')
st.cdm(
constellation='intelsat', tca='>now',
predicates=['message_for', 'tca', 'miss_distance'],
orderby='miss_distance', format='html', metadata=True)
st.cdm(
constellation='intelsat', tca='>now',
predicates=['message_for', 'tca', 'miss_distance'],
orderby='miss_distance', format='kvn')
Module Reference¶
SpaceTrack¶
-
exception
spacetrack.base.
UnknownPredicateTypeWarning
[source]¶ Used to warn when a predicate type is unknown.
-
class
spacetrack.base.
Predicate
(name, type_, nullable=False, default=None, values=None)[source]¶ Hold Space-Track predicate information.
The current goal of this class is to print the repr for the user.
-
class
spacetrack.base.
SpaceTrackClient
(identity, password, base_url='https://www.space-track.org/')[source]¶ SpaceTrack client class.
Parameters: - identity – Space-Track username.
- password – Space-Track password.
- base_url – May be overridden to use e.g. https://testing.space-track.org/
For more information, refer to the Space-Track documentation.
-
request_controllers
¶ Ordered dictionary of request controllers and their request classes in the following order.
- basicspacedata
- expandedspacedata
- fileshare
- spephemeris
For example, if the
spacetrack.file
method is used without specifying which controller, the client will choose the fileshare controller (which comes before spephemeris).Note
If new request classes and/or controllers are added to the Space-Track API but not yet to this library, you can safely subclass
SpaceTrackClient
with a copy of this ordered dictionary to add them.That said, please open an issue on GitHub for me to add them to the library.
-
session
= None¶ requests.Session
instance. It can be mutated to configure e.g. proxies.
-
authenticate
()[source]¶ Authenticate with Space-Track.
Raises: spacetrack.base.AuthenticationError
– Incorrect login details.Note
This method is called automatically when required.
-
generic_request
(class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs)[source]¶ Generic Space-Track query.
The request class methods use this method internally; the public API is as follows:
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)
They resolve to the following calls respectively:
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)
Parameters: - class_ – Space-Track request class name
- iter_lines – Yield result line by line
- iter_content – Yield result in 100 KiB chunks.
- controller – Optionally specify request controller to use.
- parse_types – Parse string values in response according to type given
in predicate information, e.g.
'2017-01-01'
->datetime.date(2017, 1, 1)
. - **kwargs –
These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet:
spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle')
See
_stringify_predicate_value()
for which Python objects are converted appropriately.
Yields: Lines—stripped of newline characters—if
iter_lines=True
Yields: 100 KiB chunks if
iter_content=True
Returns: Parsed JSON object, unless
format
keyword argument is passed.Warning
Passing
format='json'
will return the JSON unparsed. Do not setformat
if you want the parsed JSON object returned!
Experimental asyncio
API¶
Warning
The asyncio
API is not thoroughly unit tested, use with caution. Please
report issues on GitHub.
-
class
spacetrack.aio.
AsyncSpaceTrackClient
(identity, password, base_url='https://www.space-track.org/')[source]¶ Bases:
spacetrack.base.SpaceTrackClient
Asynchronous SpaceTrack client class.
This class should be considered experimental.
It must be closed by calling
close()
. Alternatively, instances of this class can be used as a context manager.Parameters: - identity – Space-Track username.
- password – Space-Track password.
- base_url – May be overridden to use e.g. https://testing.space-track.org/
For more information, refer to the Space-Track documentation.
-
session
¶ aiohttp.ClientSession
instance.
-
authenticate
()[source]¶ Authenticate with Space-Track.
Raises: spacetrack.base.AuthenticationError
– Incorrect login details.Note
This method is called automatically when required.
-
generic_request
(class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs)[source]¶ Generic Space-Track query coroutine.
The request class methods use this method internally; the public API is as follows:
st.tle_publish(*args, **st) st.basicspacedata.tle_publish(*args, **st) st.file(*args, **st) st.fileshare.file(*args, **st) st.spephemeris.file(*args, **st)
They resolve to the following calls respectively:
st.generic_request('tle_publish', *args, **st) st.generic_request('tle_publish', *args, controller='basicspacedata', **st) st.generic_request('file', *args, **st) st.generic_request('file', *args, controller='fileshare', **st) st.generic_request('file', *args, controller='spephemeris', **st)
Parameters: - class – Space-Track request class name
- iter_lines – Yield result line by line
- iter_content – Yield result in 100 KiB chunks.
- controller – Optionally specify request controller to use.
- parse_types – Parse string values in response according to type given
in predicate information, e.g.
'2017-01-01'
->datetime.date(2017, 1, 1)
. - **kwargs –
These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet:
spacetrack = AsyncSpaceTrackClient(...) await spacetrack.tle.get_predicates() # or await spacetrack.get_predicates('tle')
See
_stringify_predicate_value()
for which Python objects are converted appropriately.
Yields: Lines—stripped of newline characters—if
iter_lines=True
Yields: 100 KiB chunks if
iter_content=True
Returns: Parsed JSON object, unless
format
keyword argument is passed.Warning
Passing
format='json'
will return the JSON unparsed. Do not setformat
if you want the parsed JSON object returned!
SpaceTrack operators¶
Refer to REST Operators in the Space-Track documentation.
Change Log¶
Unreleased¶
N/A
0.13.6¶
Fixed¶
- Regression in 0.13 that prevented
spephemeris/download
from working by trying to load a model definition which it doesn’t have.
0.13.5¶
Fixed¶
- The ‘text’ predicate type is now understood.
- Unknown predicate types issue a warning instead of raising an exception.
0.13.4¶
Added¶
SpaceTrackClient
gained abase_url
parameter to allow the use of an alternate Space-Track server.
0.13.3¶
Fixed¶
- The deprecation warning about importing
Sequence
orMapping
fromcollections
instead ofcollections.abc
.
0.13.2¶
Fixed¶
- The
async
extra installs aiohttp 2 becausespacetrack
is not yet aiohttp 3 compatible. - Deprecation warnings about invalid escape sequences.
0.13.1¶
Fixed¶
spacetrack
can be installed with setuptools v38.0+, which requiresinstall_requires
insetup.py
to be ordered.
0.13.0¶
Added¶
parse_types
flag to optionally parse types as described by themodeldef
API.- Compatibility with
maneuver
andmaneuver_history
request classes forexpandedspacedata
request controller. - Compatibility with
upload
anddelete
request classes forfileshare
request controller. ### Fixed - Predicates with the enum type are parsed correctly. Previously,
single-valued enums had
None
as a second value, and enums with more than two values only had the first and last value due to the regex match not capturing repeated groups. The values aren’t used byspacetrack
, so the bug went unnoticed. - Exception on Python 3.5+ in threads without an
asyncio
event loop (even using the normalSpaceTrackClient
). Fixed by requiringratelimiter
>= 1.2.0 ### Changed - Require aiohttp >= 2.0 for the
async
extra.
0.12.0¶
Added¶
- Request controller can be passed explicitly to methods that take a request class, because some request classes are present in more than one controller.
- Request controller proxy attribute,
e.g.
SpaceTrackClient.fileshare.file()
, which is equivalent toSpaceTrackClient.generic_request('file', controller='fileshare')
. dir(SpaceTrackClient(...))
now includes the request controllers and request classes so it’s easier to see what can be called.
Fixed¶
/modeldef
API not queried if no predicates are passed. This allowsspephemeris/download
to be used, which doesn’t have a model definition.
Changed¶
- Calling request class methods uses first request controller that
matches. The order is stored in the keys of the
SpaceTrackClient.request_controllers
ordered dict, currentlybasicspacedata
,expandedspacedata
,fileshare
,spephemeris
. Any new request controllers will be added to the end, to preserve lookup order. New request classes that would change the order will accompany a major version bump. AsyncSpaceTrackClient
uses requests’ CA file for same experience with both clients.
0.11.1¶
Fixed¶
- Bump ratelimiter
version to improve rate limiting for
AsyncSpaceTrackClient
Changed¶
- Documentation included in source distribution.
0.11.0¶
Added¶
- Some unit tests added for
AsyncSpaceTrackClient
.
Fixed¶
\r\n
to\n
newline conversion for async chunk iterator.
Changed¶
AsyncSpaceTrackClient
can no longer be imported from the top levelspacetrack
module, since this would cause an error if optional dependencyaiohttp
was not installed. It must be imported fromspacetrack.aio
.
0.10.0 - 2016-02-04¶
Fixed¶
- Compatibility with
file
anddownload
request classes forfileshare
request controller.upload
request class removed, unable to test. - Rate limit violation HTTP status code 500 handled during predicate information request.
Changed¶
iter_lines=True
now raisesValueError
if receiving binary data (currently only possible withdownload
request class).- Removed internal method
_get_predicate_fields
, set comprehension used inline instead. Predicate
class now has adefault
attribute.