### Quickstart Example Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html Demonstrates connecting to the API, searching for products using a GeoJSON footprint, downloading scenes, and converting results to different formats (DataFrame, GeoJSON, GeoDataFrame). ```python # connect to the API from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt from datetime import date api = SentinelAPI('user', 'password', 'https://apihub.copernicus.eu/apihub') # download single scene by known product id api.download() # search by polygon, time, and SciHub query keywords footprint = geojson_to_wkt(read_geojson('/path/to/map.geojson')) products = api.query(footprint, date=('20151219', date(2015, 12, 29)), platformname='Sentinel-2', cloudcoverpercentage=(0, 30)) # download all results from the search api.download_all(products) # convert to Pandas DataFrame products_df = api.to_dataframe(products) # GeoJSON FeatureCollection containing footprints and metadata of the scenes api.to_geojson(products) # GeoPandas GeoDataFrame with the metadata of the scenes and the footprints as geometries api.to_geodataframe(products) # Get basic information about the product: its title, file size, MD5 sum, date, footprint and # its download url api.get_product_odata() # Get the product's full metadata available on the server api.get_product_odata(, full=True) ``` -------------------------------- ### Python API Quickstart Source: https://sentinelsat.readthedocs.io/en/stable/index.html A basic example demonstrating how to use the Sentinelsat Python API to query and download products. ```python from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt api = SentinelAPI('user', 'password') footprint = geojson_to_wkt(read_geojson('search_polygon.geojson')) products = api.query(footprint, producttype='SLC', orbitdirection='ASCENDING', limit=10) api.download_all(products) ``` -------------------------------- ### Run tests Source: https://sentinelsat.readthedocs.io/en/stable/install.html Clone the repository, install development dependencies, and run tests. ```bash git clone https://github.com/sentinelsat/sentinelsat.git cd sentinelsat pip install -e .[dev] pytest -v ``` -------------------------------- ### Install sentinelsat Source: https://sentinelsat.readthedocs.io/en/stable/install.html Install the sentinelsat library using pip. ```bash pip install sentinelsat ``` -------------------------------- ### Example Query with Product Type and Polarization Source: https://sentinelsat.readthedocs.io/en/stable/cli.html This example demonstrates how to use the `-q` or `--query` option multiple times to specify search criteria, such as product type and polarization mode. ```bash -q producttype=GRD -q polarisationmode=HH ``` -------------------------------- ### OData Example (Full Metadata) Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html This example demonstrates how to retrieve the complete metadata available for a product by setting full=True. ```python >>> api.get_product_odata('04548172-c64a-418f-8e83-7a4d148adf1e', full=True) {'Acquisition Type': 'NOMINAL', 'Carrier rocket': 'Soyuz', 'Cycle number': 107, 'Date': datetime.datetime(2017, 4, 25, 15, 56, 12, 814000), 'Filename': 'S1A_IW_SLC__1SDV_20170425T155612_20170425T155639_016302_01AF91_46FF.SAFE', 'Footprint': ' 0.401648,34.322010 0.876987,36.540989 -0.747357,36.884121 -1.227940,34.664474 0.401648,34.322010 ', 'Format': 'SAFE', 'Identifier': 'S1A_IW_SLC__1SDV_20170425T155612_20170425T155639_016302_01AF91_46FF', 'Ingestion Date': datetime.datetime(2017, 4, 25, 19, 23, 45, 956000), 'Instrument': 'SAR-C', 'Instrument abbreviation': 'SAR-C SAR', 'Instrument description': 'https://sentinel.esa.int/web/sentinel/missions/sentinel-1', 'Instrument description text': 'The SAR Antenna Subsystem (SAS) is developed and build by AstriumGmbH. It is a large foldable planar phased array antenna, which isformed by a centre panel and two antenna side wings. In deployedconfiguration the antenna has an overall aperture of 12.3 x 0.84 m.The antenna provides a fast electronic scanning capability inazimuth and elevation and is based on low loss and highly stablewaveguide radiators build in carbon fibre technology, which arealready successfully used by the TerraSAR-X radar imaging mission.The SAR Electronic Subsystem (SES) is developed and build byAstrium Ltd. It provides all radar control, IF/ RF signalgeneration and receive data handling functions for the SARInstrument. The fully redundant SES is based on a channelisedarchitecture with one transmit and two receive chains, providing amodular approach to the generation and reception of wide-bandsignals and the handling of multi-polarisation modes. One keyfeature is the implementation of the Flexible Dynamic BlockAdaptive Quantisation (FD-BAQ) data compression concept, whichallows an efficient use of on-board storage resources and minimisesdownlink times.', 'Instrument mode': 'IW', 'Instrument name': 'Synthetic Aperture Radar (C-band)', 'Instrument swath': 'IW1 IW2 IW3', 'JTS footprint': 'POLYGON ((34.322010 0.401648,36.540989 0.876987,36.884121 -0.747357,34.664474 -1.227940,34.322010 0.401648))', 'Launch date': 'April 3rd, 2014', 'Mission datatake id': 110481, 'Mission type': 'Earth observation', 'Mode': 'IW', 'NSSDC identifier': '2014-016A', 'Operator': 'European Space Agency', 'Orbit number (start)': 16302, 'Orbit number (stop)': 16302, 'Pass direction': 'ASCENDING', 'Phase identifier': 1, 'Polarisation': 'VV VH', 'Product class': 'S', 'Product class description': 'SAR Standard L1 Product', 'Product composition': 'Slice', 'Product level': 'L1', 'Product type': 'SLC', 'Relative orbit (start)': 130, 'Relative orbit (stop)': 130, 'Satellite': 'Sentinel-1', 'Satellite description': 'https://sentinel.esa.int/web/sentinel/missions/sentinel-1', 'Satellite name': 'Sentinel-1', 'Satellite number': 'A', 'Sensing start': datetime.datetime(2017, 4, 25, 15, 56, 12, 814000), 'Sensing stop': datetime.datetime(2017, 4, 25, 15, 56, 39, 758000), 'Size': '7.1 GB', 'Slice number': 8, 'Start relative orbit number': 130, 'Status': 'ARCHIVED', 'Stop relative orbit number': 130, 'Timeliness Category': 'Fast-24h', 'date': datetime.datetime(2017, 4, 25, 15, 56, 12, 814000), 'footprint': 'POLYGON((34.322010 0.401648,36.540989 0.876987,36.884121 -0.747357,34.664474 -1.227940,34.322010 0.401648))', 'id': '04548172-c64a-418f-8e83-7a4d148adf1e', 'md5': 'E5855D1C974171D33EE4BC08B9D221AE', 'size': 4633501134, 'title': 'S1A_IW_SLC__1SDV_20170425T155612_20170425T155639_016302_01AF91_46FF'} ``` -------------------------------- ### OData example Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html Example of an OData query to retrieve product data. ```json { "url": "https://apihub.copernicus.eu/apihub/odata/v1/Products('04548172-c64a-418f-8e83-7a4d148adf1e')/$value" } ``` -------------------------------- ### Command Line Interface Example Source: https://sentinelsat.readthedocs.io/en/stable/index.html An example of how to use the sentinelsat command line interface to search for Sentinel-2 images. ```bash sentinelsat -u -p --location Berlin --sentinel 2 --cloud 30 --start NOW-1MONTH ``` -------------------------------- ### OData Example (Basic) Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html This example shows how to retrieve basic OData information for a product without requesting full metadata. ```python >>> api.get_product_odata('04548172-c64a-418f-8e83-7a4d148adf1e') {'date': datetime.datetime(2017, 4, 25, 15, 56, 12, 814000), 'footprint': 'POLYGON((34.322010 0.401648,36.540989 0.876987,36.884121 -0.747357,34.664474 -1.227940,34.322010 0.401648))', 'id': '04548172-c64a-418f-8e83-7a4d148adf1e', 'md5': 'E5855D1C974171D33EE4BC08B9D221AE', 'size': 4633501134, 'title': 'S1A_IW_SLC__1SDV_20170425T155612_20170425T155639_016302_01AF91_46FF', 'url': "https://apihub.copernicus.eu/apihub/odata/v1/Products('04548172-c64a-418f-8e83-7a4d148adf1e')/$value"} ``` -------------------------------- ### OpenSearch Example Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html Example of querying OpenSearch for Sentinel-1 SLC products within the last 8 hours. ```python >>> api.query(date=('NOW-8HOURS', 'NOW'), producttype='SLC') OrderedDict([('04548172-c64a-418f-8e83-7a4d148adf1e', {'acquisitiontype': 'NOMINAL', 'beginposition': datetime.datetime(2017, 4, 25, 15, 56, 12, 814000), 'endposition': datetime.datetime(2017, 4, 25, 15, 56, 39, 758000), 'filename': 'S1A_IW_SLC__1SDV_20170425T155612_20170425T155639_016302_01AF91_46FF.SAFE', 'footprint': 'POLYGON ((34.322010 0.401648,36.540989 0.876987,36.884121 -0.747357,34.664474 -1.227940,34.322010 0.401648))', 'format': 'SAFE', 'gmlfootprint': ' 0.401648,34.322010 0.876987,36.540989 -0.747357,36.884121 -1.227940,34.664474 0.401648,34.322010 ', 'identifier': 'S1A_IW_SLC__1SDV_20170425T155612_20170425T155639_016302_01AF91_46FF', 'ingestiondate': datetime.datetime(2017, 4, 25, 19, 23, 45, 956000), 'instrumentname': 'Synthetic Aperture Radar (C-band)', 'instrumentshortname': 'SAR-C SAR', 'lastorbitnumber': 16302, 'lastrelativeorbitnumber': 130, 'link': "https://apihub.copernicus.eu/apihub/odata/v1/Products('04548172-c64a-418f-8e83-7a4d148adf1e')/$value", 'link_alternative': "https://apihub.copernicus.eu/apihub/odata/v1/Products('04548172-c64a-418f-8e83-7a4d148adf1e')/", 'link_icon': "https://apihub.copernicus.eu/apihub/odata/v1/Products('04548172-c64a-418f-8e83-7a4d148adf1e')/Products('Quicklook')/$value", 'missiondatatakeid': 110481, 'orbitdirection': 'ASCENDING', 'orbitnumber': 16302, 'platformidentifier': '2014-016A', 'platformname': 'Sentinel-1', 'polarisationmode': 'VV VH', 'productclass': 'S', 'producttype': 'SLC', 'relativeorbitnumber': 130, 'sensoroperationalmode': 'IW', 'size': '7.1 GB', 'slicenumber': 8, 'status': 'ARCHIVED', 'summary': 'Date: 2017-04-25T15:56:12.814Z, Instrument: SAR-C SAR, Mode: VV VH, Satellite: Sentinel-1, Size: 7.1 GB', 'swathidentifier': 'IW1 IW2 IW3', 'title': 'S1A_IW_SLC__1SDV_20170425T155612_20170425T155639_016302_01AF91_46FF', 'uuid': '04548172-c64a-418f-8e83-7a4d148adf1e'}) ... ``` -------------------------------- ### get_product_odata Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Accesses OData API to get info about a product. Returns a dict containing the id, title, size, md5sum, date, footprint and download url of the product. The date field corresponds to the Start ContentDate value. If full is set to True, then the full, detailed metadata of the product is returned in addition to the above. ```python get_product_odata(_id_ , _full=False) ``` -------------------------------- ### get_stream example Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Exposes requests response ready to stream product to e.g. S3. ```python get_stream(_id_ , _**kwargs_) ``` -------------------------------- ### Configure Copernicus Open Access Hub credentials for tests Source: https://sentinelsat.readthedocs.io/en/stable/install.html Set environment variables for Copernicus Open Access Hub username and password to allow tests to run actual queries. Also, includes an option to disable VCR for testing. ```bash export DHUS_USER= export DHUS_PASSWORD= ``` -------------------------------- ### __repr__ Method Example Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html Provides a string representation of the handler, including its class name and logging level. ```python def __repr__(self): level = getLevelName(self.level) return '<%s (%s)>' % (self.__class__.__name__, level) ``` -------------------------------- ### Example of make_path_filter usage Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html An example of using the make_path_filter helper function to create a nodefilter that excludes files matching a glob pattern. ```python path_filter = make_path_filter("*measurement/*", exclude=True) ``` -------------------------------- ### Example node_info dictionary keys Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html The keys available in the node_info dictionary passed to the nodefilter function. ```python url:| the URL to download the product file node node_path:| the _path_ within the product (e.g. ".//preview/map-overlay.kml") size:| the file size in bytes (int) md5:| the file’s MD5 checksum ``` -------------------------------- ### Sorting and Filtering Example Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html Demonstrates querying Sentinel-2 scenes, converting results to a Pandas DataFrame, sorting by cloud cover and ingestion date, limiting results, and downloading the selected scenes. ```python # connect to the API from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt from datetime import date api = SentinelAPI('user', 'password', 'https://apihub.copernicus.eu/apihub') # search by polygon, time, and SciHub query keywords footprint = geojson_to_wkt(read_geojson('map.geojson')) products = api.query(footprint, date=('20151219', date(2015, 12, 29)), platformname='Sentinel-2') # convert to Pandas DataFrame products_df = api.to_dataframe(products) # sort and limit to first 5 sorted products products_df_sorted = products_df.sort_values(['cloudcoverpercentage', 'ingestiondate'], ascending=[True, True]) products_df_sorted = products_df_sorted.head(5) # download sorted and reduced products api.download_all(products_df_sorted.index) ``` -------------------------------- ### make_path_filter example Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Generate a nodefilter function to download only files matching the specified pattern. ```python make_path_filter(_pattern_ , _exclude=False_) ``` -------------------------------- ### all_nodes_filter example Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Node filter function to download all files. This function can be used to download a Sentinel product as a directory instead of downloading a single zip archive. New in version 0.15. ```python all_nodes_filter(_node_info_) ``` -------------------------------- ### make_size_filter example Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Generate a nodefilter function to download only files below the specified maximum size. New in version 0.15. ```python make_size_filter(_max_size_) ``` -------------------------------- ### Get total product size Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Calculates the total file size in GB for a list of products. ```python get_products_size(products) ``` -------------------------------- ### placename_to_wkt example Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Geocodes the place name to rectangular bounding extents using Nominatim API and returns the corresponding ‘ENVELOPE’ form Well-Known-Text. ```python placename_to_wkt(_place_name_) ``` -------------------------------- ### Download all quicklooks Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Downloads quicklooks for a list of products. The input can be the output of the query() method. ```python download_all_quicklooks(products, directory_path='.', n_concurrent_dl=4) ``` -------------------------------- ### Download a single quicklook Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Downloads a quicklook for a specific product ID. Already downloaded images are skipped. ```python download_quicklook(id, directory_path='.') ``` -------------------------------- ### .netrc File for Credentials Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Alternatively, you can add your credentials to a file .netrc in your user home directory. ```bash machine apihub.copernicus.eu login password ``` -------------------------------- ### download_all Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Downloads a list of products. Takes a list of product IDs as input. This means that the return value of query() can be passed directly to this method. ```python download_all(_products_ , _directory_path='.'_ , _max_attempts=10_ , _checksum=True_ , _n_concurrent_dl=None_ , _lta_retry_delay=None_ , _fail_fast=False_ , _nodefilter=None) ``` -------------------------------- ### Logger getChild method Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html This method gets a child logger, which is a descendant of the current logger. ```python def getChild(self, suffix): """ Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix) ``` -------------------------------- ### Sentinel-1 Download by Filename Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Download a single Sentinel-1 GRDH scene by using its filename. ```bash sentinelsat -u -p -d --name S1A_EW_GRDM_1SDH_20151224T154142_20151224T154207_009186_00D3B0_C71E ``` -------------------------------- ### Logger getEffectiveLevel method Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html This method gets the effective level for a logger by looping through its parents. ```python def getEffectiveLevel(self): """ Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found. """ logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET ``` -------------------------------- ### Sentinel-2 Search and Download Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Search and download Sentinel-2 scenes for January 2016 with a maximum cloud cover of 40%. ```bash sentinelsat -u -p -g -s 20160101 -e 20160131 --sentinel 2 --cloud 40 -d ``` -------------------------------- ### Get Product OData Source: https://sentinelsat.readthedocs.io/en/stable/_modules/sentinelsat/sentinel.html Accesses the OData API to retrieve information about a specific product. ```python [docs] def get_product_odata(self, id, full=False): """Access OData API to get info about a product. Returns a dict containing the id, title, size, md5sum, date, footprint and download url of the product. The date field corresponds to the Start ContentDate value. If `full` is set to True, then the full, detailed metadata of the product is returned in addition to the above. Parameters ---------- id : string The UUID of the product to query full : bool Whether to get the full metadata for the Product. False by default. Returns ------- dict[str, Any] A dictionary with an item for each metadata attribute Notes ----- For a full list of mappings between the OpenSearch (Solr) and OData attribute names see the following definition files: https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl """ ``` -------------------------------- ### Orbit Products Search Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Search precise orbit products (“AUX_POEORB”) for Sentinel-1B for a specific date. ```bash sentinelsat --gnss -s 20210201 -e 20210202 --producttype AUX_POEORB --query="platformserialidentifier=1B" ``` -------------------------------- ### Example nodefilter function signature Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html The signature for a nodefilter function, which is called for each file in a product to determine if it should be downloaded. ```python def nodefilter(node_info: dict) -> bool: ... ``` -------------------------------- ### Command with Stored Credentials Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Environment variables take precedence over .netrc. The command then becomes: ```bash sentinelsat -g ``` -------------------------------- ### Basic Search Query Source: https://sentinelsat.readthedocs.io/en/stable/cli.html A basic search query consists of a search polygon as well as the username and password to access the Copernicus Open Access Hub. ```bash sentinelsat -u -p -g ``` -------------------------------- ### Authentication using .netrc Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html Shows how to configure authentication credentials in a .netrc file for use with SentinelAPI. ```text machine apihub.copernicus.eu login password ``` -------------------------------- ### Download all products Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Downloads all products from a list of product IDs to a specified directory, with options for retries, checksum verification, concurrent downloads, and fail-fast behavior. ```python download_all( products, directory_path='.', max_attempts=10, checksum=True, n_concurrent_dl=None, lta_retry_delay=60, fail_fast=False, nodefilter=None ) ``` -------------------------------- ### handleError Method Example Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html This method handles errors during emit() calls, writing details to sys.stderr if raiseExceptions is true. ```python def handleError(self, record): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. """ if raiseExceptions and sys.stderr: # see issue 13807 t, v, tb = sys.exc_info() try: sys.stderr.write('--- Logging error ---\n') traceback.print_exception(t, v, tb, None, sys.stderr) sys.stderr.write('Call stack:\n') # Walk the stack frame up until we're out of logging, # so as to print the calling context. frame = tb.tb_frame while (frame and os.path.dirname(frame.f_code.co_filename) == __path__[0]): frame = frame.f_back if frame: traceback.print_stack(frame, file=sys.stderr) else: # couldn't find the right stack frame, for some reason sys.stderr.write('Logged from file %s, line %s\n' % ( record.filename, record.lineno)) # Issue 18671: output logging message and arguments try: sys.stderr.write('Message: %r\n' 'Arguments: %s\n' % (record.msg, record.args)) except RecursionError: # See issue 36272 raise except Exception: sys.stderr.write('Unable to print the message and arguments' ' - possible formatting error.\nUse the' ' traceback above to help find the error.\n' ) except OSError: #pragma: no cover pass # see issue 5971 finally: del t, v, tb ``` -------------------------------- ### Sentinel-2 Download Last 24 Hours Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Download all Sentinel-2 scenes published in the last 24 hours. ```bash sentinelsat -u -p -g --sentinel 2 -d ``` -------------------------------- ### Current Frame Retrieval Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html Defines a way to get the current frame object, with a fallback for environments where sys._getframe is not available. ```python if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) else: #pragma: no cover def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except Exception: return sys.exc_info()[2].tb_frame.f_back ``` -------------------------------- ### Handler Class Example Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html This snippet shows how a handler might acquire a lock, update a shared structure, and release the lock. ```python _acquireLock() try: if self._name and self._name in _handlers: del _handlers[self._name] finally: _releaseLock() ``` -------------------------------- ### geojson_to_wkt example Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries. 3D points are converted to 2D. ```python geojson_to_wkt(_geojson_obj_ , _decimals=4_) ``` -------------------------------- ### LoggerAdapter __init__ method Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html Initializes the adapter with a logger and contextual information. ```python def __init__(self, logger, extra): """ Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) """ self.logger = logger self.extra = extra ``` -------------------------------- ### Downloading specific parts of a product Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html Uses a node filter to download only specific files within a product, excluding measurement files in this example. ```python from sentinelsat import SentinelAPI, make_path_filter # define the filter function to select files (to be excluded in this case) path_filter = make_path_filter("*measurement/*", exclude=True) # connect to the API api = SentinelProductAPI("user", "password") # download a single product excluding measurement files api.download(, nodefilter=path_filter) ``` -------------------------------- ### Sentinel-1 Search and Download Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Search and download all Sentinel-1 scenes of type SLC over a search polygon, in descending orbit for the year 2015. ```bash sentinelsat -u -p -g -s 20150101 -e 20151231 -d \ --producttype SLC -q "orbitdirection=Descending" \ --url "https://apihub.copernicus.eu/apihub" ``` -------------------------------- ### Get stream for product Source: https://sentinelsat.readthedocs.io/en/stable/_modules/sentinelsat/sentinel.html Exposes the requests response object, ready to stream a product to a destination like S3. It takes a product ID and optional keyword arguments for requests.get(). ```python def get_stream(self, id, **kwargs): """Exposes requests response ready to stream product to e.g. S3. Parameters ---------- id : string UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed' **kwargs Any additional parameters for :func:`requests.get()` Raises ------ LTATriggered If the product has been archived and its retrieval was successfully triggered. LTAError If the product has been archived and its retrieval failed. Returns ------- requests.Response: Opened response object """ return self.downloader.get_stream(id, **kwargs) ``` -------------------------------- ### Check product files Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Verifies the integrity of product files on disk by comparing size and checksum with server values. Can optionally delete files. ```python check_files(paths=None, ids=None, directory=None, delete=False) ``` -------------------------------- ### RootLogger __init__ method Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html Initializes the root logger. ```python def __init__(self, level): """ Initialize the logger with the name "root". """ Logger.__init__(self, "root", level) ``` -------------------------------- ### count Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Gets the number of products matching a query. Accepted parameters are identical to SentinelAPI.query(). This is a significantly more efficient alternative to doing len(api.query()), which can take minutes to run for queries matching thousands of products. ```python count(_area=None , _date=None , _raw=None , _area_relation='Intersects'_ , _**keywords) ``` -------------------------------- ### Sentinel-1 Download by UUID Source: https://sentinelsat.readthedocs.io/en/stable/cli.html Download a single Sentinel-1 GRDH scene covering Santa Claus Village in Finland on Christmas Eve 2015. ```bash sentinelsat -u -p -d --uuid a9048d1d-fea6-4df8-bedd-7bcb212be12e ``` -------------------------------- ### Get Products Size Source: https://sentinelsat.readthedocs.io/en/stable/_modules/sentinelsat/sentinel.html Calculates the total file size of all products in an OpenSearch response, converting sizes from MB or KB to GB and returning the total size rounded to two decimal places. ```python size_total = 0 for title, props in products.items(): size_product = props["size"] size_value = float(size_product.split(" ")[0]) size_unit = str(size_product.split(" ")[1]) if size_unit == "MB": size_value /= 1024.0 if size_unit == "KB": size_value /= 1024.0 * 1024.0 size_total += size_value return round(size_total, 2) ``` -------------------------------- ### FileHandler __init__ Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html Initializes the FileHandler, opening the specified file for logging. ```python def __init__(self, filename, mode='a', encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. """ # Issue #27493: add support for Path objects to be passed in filename = os.fspath(filename) #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes self.baseFilename = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.delay = delay if delay: #We don't open the stream, but we still need to call the #Handler constructor to set level, formatter, lock etc. Handler.__init__(self) self.stream = None else: StreamHandler.__init__(self, self._open()) ``` -------------------------------- ### Download specific channels of a Sentinel-1 product Source: https://sentinelsat.readthedocs.io/en/stable/api_overview.html Downloads only specific polarization measurement files (e.g., HH) for specified sub-swaths (e.g., EW1 and EW2) of Sentinel-1 SLC products. ```python path_filter = make_path_filter("*s1?-ew[12]-slc-hh-*.tiff") ``` -------------------------------- ### format_query_date example Source: https://sentinelsat.readthedocs.io/en/stable/api_reference.html Format a date, datetime or a YYYYMMDD string input as YYYY-MM-DDThh:mm:ssZ or validate a date string as suitable for the full text search interface and return it. None will be converted to ‘*’, meaning an unlimited date bound in date ranges. ```python format_query_date(_in_date_) ``` -------------------------------- ### Manager.getLogger Source: https://sentinelsat.readthedocs.io/en/stable/_modules/logging.html Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. ```python def getLogger(self, name): """ Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. """ rv = None if not isinstance(name, str): raise TypeError('A logger name must be a string') _acquireLock() try: if name in self.loggerDict: rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupChildren(ph, rv) self._fixupParents(rv) else: rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupParents(rv) finally: _releaseLock() return rv ``` -------------------------------- ### Environment Variables for Credentials Source: https://sentinelsat.readthedocs.io/en/stable/cli.html For convenience and added security, you can set username, password and DHuS URL as environment variables. ```bash export DHUS_USER="" export DHUS_PASSWORD="" export DHUS_URL="" ```