### Install Development Dependencies Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Installs the necessary packages for development, including testing and code quality tools. This command assumes you have pip installed. ```console pip install -U -r tests/requirements-dev.txt ``` -------------------------------- ### Install cdsapi using pip Source: https://github.com/ecmwf/cdsapi/blob/master/README.rst This command installs the cdsapi Python package using pip. Ensure you have Python and pip installed on your system. ```bash pip install cdsapi ``` -------------------------------- ### Perform Quality Check Release Steps Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Executes pre-release quality checks, including checking git status, validating package manifest with `check-manifest`, and running tests with `tox`. ```console git status check-manifest tox ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Executes unit tests using pytest, with options for verbose output, flake8 checks, code coverage reporting (HTML), and cache clearing. Ensure pytest is installed. ```console pytest -v --flakes --cov=cdsapi --cov-report=html --cache-clear ``` -------------------------------- ### Call CDS Service Endpoint (Python) Source: https://context7.com/ecmwf/cdsapi/llms.txt This example demonstrates how to use `client.service()` to call advanced CDS service endpoints beyond simple data retrieval. It shows how to pass both positional and keyword arguments, and how to mimic the CDS UI behavior for specific service calls. ```Python import cdsapi client = cdsapi.Client() # Call a service with positional and keyword arguments result = client.service( "tool.toolbox.orchestrator", "arg1", "arg2", param1="value1", param2="value2" ) # Call service mimicking the CDS UI behavior result = client.service( "some.service.name", mimic_ui=True, variable="temperature", format="netcdf" ) ``` -------------------------------- ### Update Test Requirements Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Updates the `requirements-tests.txt` file by recompiling dependencies from `setup.py` and `tests/requirements-tests.in`. The `-U` flag is optional and upgrades existing packages. ```console pip-compile -U -o tests/requirements-tests.txt setup.py tests/requirements-tests.in ``` -------------------------------- ### Execute Release Procedure with Zest.releaser Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Performs the release process using the zest.releaser tool. This involves running pre-release, release, and post-release steps. ```console prerelease release postrelease ``` -------------------------------- ### Docker Usage for CDS Data Retrieval (Bash) Source: https://context7.com/ecmwf/cdsapi/llms.txt This bash command demonstrates how to run the cdsapi Docker container. It mounts the current directory for output and a specific `request.json` file for input. This setup is useful for automated or reproducible data retrieval tasks. ```Bash # Run the Docker container with mounted request and output directories docker run -it --rm \ -v $(pwd)/request.json:/input/request.json \ -v $(pwd):/output \ cdsapi/cdsretrieve ``` -------------------------------- ### Run Code Quality Checks Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Performs code quality checks using pytest, specifically for PEP 8 style guide compliance and McCabe complexity. Ensure pytest is installed. ```console pytest -v --pep8 --mccabe ``` -------------------------------- ### Run Python Version Tests with Tox Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Executes tests across multiple Python versions using tox. This ensures compatibility with different Python environments. Ensure tox is installed. ```console tox ``` -------------------------------- ### Create Result Object from Remote URL (Python) Source: https://context7.com/ecmwf/cdsapi/llms.txt This example shows how to use `client.remote()` to create a Result object from a remote URL. This allows leveraging the cdsapi's download infrastructure for files hosted externally. The downloaded file can then be saved using the `download()` method. ```Python import cdsapi client = cdsapi.Client() # Create a Result object from an external URL result = client.remote("https://example.com/data/climate_data.nc") # Download using cdsapi's robust download mechanism result.download("external_data.nc") ``` -------------------------------- ### Retrieve Data with cdsapi Client Source: https://context7.com/ecmwf/cdsapi/llms.txt Shows how to use the `client.retrieve()` method to fetch climate data from CDS. Examples include retrieving ERA5 single-level and pressure-level data, and glacier elevation change data, with options for specifying output format and download destination. ```python import cdsapi client = cdsapi.Client() # Retrieve ERA5 single-level reanalysis data (2m temperature) result = client.retrieve( "reanalysis-era5-single-levels", { "variable": "2t", # 2m temperature "product_type": "reanalysis", "date": "2012-12-01", "time": "14:00", "format": "netcdf", }, ) result.download("temperature.nc") ``` ```python # Retrieve ERA5 pressure level data with date range client.retrieve( "reanalysis-era5-pressure-levels", { "variable": "temperature", "pressure_level": "1000", "product_type": "reanalysis", "date": "2017-12-01/2017-12-31", "time": "12:00", "format": "grib", }, "era5_pressure.grib" # Download directly to file ) ``` ```python # Retrieve glacier elevation change data client.retrieve( "insitu-glaciers-elevation-mass", { "variable": "elevation_change", "format": "tgz", }, "glaciers.tgz" ) ``` -------------------------------- ### Open Coverage Report Source: https://github.com/ecmwf/cdsapi/blob/master/CONTRIBUTING.rst Opens the generated HTML code coverage report in the default web browser. This requires the coverage report to have been generated previously (e.g., by pytest). ```console open htmlcov/index.html ``` -------------------------------- ### Client.retrieve() - Synchronous Data Retrieval Source: https://context7.com/ecmwf/cdsapi/llms.txt Submits a data retrieval request and waits for the download to complete. Examples include ERA5 data and glacier data. ```APIDOC ## Client.retrieve() - Synchronous Retrieval Submits a data retrieval request to the CDS and optionally downloads the result. This is the primary method for obtaining climate data from available datasets. ### Example 1: Retrieve ERA5 single-level reanalysis data (2m temperature) ```python import cdsapi client = cdsapi.Client() result = client.retrieve( "reanalysis-era5-single-levels", { "variable": "2t", # 2m temperature "product_type": "reanalysis", "date": "2012-12-01", "time": "14:00", "format": "netcdf", }, ) result.download("temperature.nc") ``` ### Example 2: Retrieve ERA5 pressure level data with date range and download directly to file ```python import cdsapi client = cdsapi.Client() client.retrieve( "reanalysis-era5-pressure-levels", { "variable": "temperature", "pressure_level": "1000", "product_type": "reanalysis", "date": "2017-12-01/2017-12-31", "time": "12:00", "format": "grib", }, "era5_pressure.grib" # Download directly to file ) ``` ### Example 3: Retrieve glacier elevation change data ```python import cdsapi client = cdsapi.Client() client.retrieve( "insitu-glaciers-elevation-mass", { "variable": "elevation_change", "format": "tgz", }, "glaciers.tgz" ) ``` ``` -------------------------------- ### Retrieve ERA5 data using cdsapi in Python Source: https://github.com/ecmwf/cdsapi/blob/master/README.rst This Python code snippet demonstrates how to use the cdsapi client to retrieve ERA5 pressure-level data for a specified date range and time. It requires the cdsapi package to be installed and configured. ```python import cdsapi cds = cdsapi.Client() cds.retrieve('reanalysis-era5-pressure-levels', { "variable": "temperature", "pressure_level": "1000", "product_type": "reanalysis", "date": "2017-12-01/2017-12-31", "time": "12:00", "format": "grib" }, 'download.grib') ``` -------------------------------- ### Initialize cdsapi Client Source: https://context7.com/ecmwf/cdsapi/llms.txt Demonstrates various ways to initialize the `cdsapi.Client` class, including basic initialization using default configuration, full initialization with explicit parameters, and using environment variables for credentials. ```python import cdsapi # Basic initialization - reads credentials from ~/.cdsapirc client = cdsapi.Client() ``` ```python import cdsapi # Full initialization with all options client = cdsapi.Client( url="https://cds.climate.copernicus.eu/api", # CDS API URL key="UID:API-KEY", # Authentication key quiet=False, # Enable/disable logging debug=False, # Enable debug messages verify=True, # SSL certificate verification timeout=60, # Request timeout in seconds progress=True, # Show download progress bar retry_max=500, # Maximum retry attempts sleep_max=120, # Maximum sleep between retries wait_until_complete=True, # Wait for job completion delete=True, # Auto-delete job after download ) ``` ```python # Using environment variables instead of config file # Set CDSAPI_URL and CDSAPI_KEY environment variables import os os.environ["CDSAPI_URL"] = "https://cds.climate.copernicus.eu/api" os.environ["CDSAPI_KEY"] = "UID:API-KEY" client = cdsapi.Client() ``` -------------------------------- ### cdsapi.Client Initialization Source: https://context7.com/ecmwf/cdsapi/llms.txt Demonstrates how to initialize the cdsapi Client class with various options for connection and request handling. ```APIDOC ## cdsapi.Client The main entry point for interacting with the Climate Data Store. Initializes a connection with authentication and provides methods for data retrieval, service calls, and status checking. ### Basic Initialization Reads credentials from `~/.cdsapirc` by default. ```python import cdsapi client = cdsapi.Client() ``` ### Full Initialization with Options Allows explicit configuration of connection and request parameters. ```python import cdsapi client = cdsapi.Client( url="https://cds.climate.copernicus.eu/api", # CDS API URL key="UID:API-KEY", # Authentication key quiet=False, # Enable/disable logging debug=False, # Enable debug messages verify=True, # SSL certificate verification timeout=60, # Request timeout in seconds progress=True, # Show download progress bar retry_max=500, # Maximum retry attempts sleep_max=120, # Maximum sleep between retries wait_until_complete=True, # Wait for job completion delete=True, # Auto-delete job after download ) ``` ``` -------------------------------- ### Configuration Source: https://context7.com/ecmwf/cdsapi/llms.txt Instructions on how to configure the cdsapi client using a `.cdsapirc` file or environment variables. ```APIDOC ## Configuration Before using cdsapi, you must configure your credentials by creating a `.cdsapirc` file with your Personal Access Token from the CDS portal. ```bash # Create the configuration file at ~/.cdsapirc cat > ~/.cdsapirc << 'EOF' url: https://cds.climate.copernicus.eu/api key: EOF ``` Alternatively, you can set the `CDSAPI_URL` and `CDSAPI_KEY` environment variables. ```python import os os.environ["CDSAPI_URL"] = "https://cds.climate.copernicus.eu/api" os.environ["CDSAPI_KEY"] = "UID:API-KEY" ``` ``` -------------------------------- ### Configure cdsapi Credentials Source: https://context7.com/ecmwf/cdsapi/llms.txt Sets up the necessary configuration file (`.cdsapirc`) in the user's home directory with the CDS API URL and a Personal Access Token for authentication. ```bash # Create the configuration file at ~/.cdsapirc cat > ~/.cdsapirc << 'EOF' url: https://cds.climate.copernicus.eu/api key: EOF ``` -------------------------------- ### Configure cdsapi with Personal Access Token Source: https://github.com/ecmwf/cdsapi/blob/master/README.rst This shows how to configure the cdsapi by creating a configuration file (~/.cdsapirc) and adding your CDS portal API key. This is necessary for authentication when retrieving data. ```bash cat ~/.cdsapirc url: https://cds.climate.copernicus.eu/api key: ``` -------------------------------- ### Docker Usage for CDS Data Retrieval (JSON and Bash) Source: https://context7.com/ecmwf/cdsapi/llms.txt This section provides instructions for using the cdsapi within a Docker container. It includes a sample `request.json` file defining the data request parameters and a bash command to run the container, mounting local directories for input and output. This enables isolated and reproducible data retrieval workflows. ```JSON // request.json { "url": "https://cds.climate.copernicus.eu/api/v2", "uuid": "", "key": "", "variable": "reanalysis-era5-pressure-levels", "options": { "variable": "temperature", "pressure_level": "1000", "product_type": "reanalysis", "date": "2017-12-01/2017-12-31", "time": "12:00", "format": "grib" }, "filename": "output.grib" } ``` -------------------------------- ### Initialize and Use CDS API Client for Data Retrieval (Python) Source: https://context7.com/ecmwf/cdsapi/llms.txt This code initializes the CDS API client and retrieves data for a specific dataset ('reanalysis-era5-single-levels'). It shows how to access result metadata like content length, type, and download location. It also demonstrates checking file availability on the server, downloading to a specific file, converting the result to JSON, and manually deleting the job from the server. ```Python import cdsapi client = cdsapi.Client() result = client.retrieve( "reanalysis-era5-single-levels", { "variable": "2t", "product_type": "reanalysis", "date": "2012-12-01", "time": "12:00", }, ) # Access result metadata print(f"Content Length: {result.content_length} bytes") print(f"Content Type: {result.content_type}") print(f"Download Location: {result.location}") # Check file availability on server metadata = result.check() # Performs HEAD request print(f"Server Headers: {metadata.headers}") # Download to specific file result.download("my_data.grib") # Convert result to JSON representation json_data = result.toJSON() # Returns: {"resultType": "url", "contentType": "...", "contentLength": ..., "location": "..."} # Manually delete job from server (if delete=False was set) result.delete() ``` -------------------------------- ### Asynchronous Data Retrieval with cdsapi Source: https://context7.com/ecmwf/cdsapi/llms.txt Illustrates how to perform asynchronous data retrieval by setting `wait_until_complete=False` during client initialization. This allows for manual polling of the job status instead of blocking until completion, useful for custom progress handling. ```python import time import cdsapi # Initialize client with wait_until_complete=False client = cdsapi.Client(debug=True, wait_until_complete=False) # Submit request without waiting result = client.retrieve( "reanalysis-era5-single-levels", { "variable": "2t", "product_type": "reanalysis", "date": "2015-12-01", "time": "14:00", "format": "netcdf", }, ) ``` -------------------------------- ### Execute CDS Workflow (Python) Source: https://context7.com/ecmwf/cdsapi/llms.txt This snippet illustrates how to execute a workflow using `client.workflow()`. This method is used for complex data processing pipelines managed by the CDS toolbox orchestrator. It requires the workflow code and any necessary parameters. ```Python import cdsapi client = cdsapi.Client() # Execute a workflow with code and parameters result = client.workflow( code="workflow_code_here", workflow_name="custom_workflow", param1="value1" ) ``` -------------------------------- ### Configure Custom Logging Callbacks (Python) Source: https://context7.com/ecmwf/cdsapi/llms.txt This Python code shows how to set up custom callback functions for logging messages (info, warning, error, debug) instead of using the default logger. This allows for more control over how log messages are handled and displayed. The custom callbacks are passed to the `cdsapi.Client` constructor. ```Python import cdsapi def my_info(msg, *args, **kwargs): print(f"[INFO] {msg % args if args else msg}") def my_warning(msg, *args, **kwargs): print(f"[WARNING] {msg % args if args else msg}") def my_error(msg, *args, **kwargs): print(f"[ERROR] {msg % args if args else msg}") def my_debug(msg, *args, **kwargs): print(f"[DEBUG] {msg % args if args else msg}") client = cdsapi.Client( info_callback=my_info, warning_callback=my_warning, error_callback=my_error, debug_callback=my_debug, debug=True ) # Now all log messages go through custom callbacks result = client.retrieve( "reanalysis-era5-single-levels", {"variable": "2t", "product_type": "reanalysis", "date": "2012-01-01", "time": "12:00"}, "output.grib" ) ``` -------------------------------- ### Client.retrieve() - Asynchronous Retrieval with Status Polling Source: https://context7.com/ecmwf/cdsapi/llms.txt Demonstrates how to submit a request without waiting for completion, allowing for manual status polling and custom progress handling. ```APIDOC ## Client.retrieve() - Asynchronous Retrieval For long-running requests, you can disable automatic waiting (`wait_until_complete=False`) and manually poll for completion status. This allows for custom progress handling and logging. ```python import time import cdsapi # Initialize client with wait_until_complete=False client = cdsapi.Client(debug=True, wait_until_complete=False) # Submit request without waiting result = client.retrieve( "reanalysis-era5-single-levels", { "variable": "2t", "product_type": "reanalysis", "date": "2015-12-01", "time": "14:00", "format": "netcdf", }, ) # You can then poll the status of the 'result' object manually # For example: # while result.status != 'completed': # print(f"Job status: {result.status}") # time.sleep(60) # result.download("temperature_async.nc") ``` ``` -------------------------------- ### Client.workflow() Source: https://context7.com/ecmwf/cdsapi/llms.txt Executes a workflow through the CDS toolbox orchestrator for complex data processing pipelines. ```APIDOC ## Client.workflow() ### Description Executes a workflow through the CDS toolbox orchestrator, allowing for complex data processing pipelines to be run. ### Method `client.workflow(code, workflow_name, *args, **kwargs)` ### Endpoint N/A (Internal client method) ### Parameters #### Path Parameters - **code** (string) - The code defining the workflow. - **workflow_name** (string) - The name of the workflow to execute. #### Query Parameters - **param1, param2, ...** (any) - Parameters required by the workflow. ### Request Example ```python import cdsapi client = cdsapi.Client() # Execute a workflow with code and parameters result = client.workflow( code="workflow_code_here", workflow_name="custom_workflow", param1="value1" ) ``` ### Response #### Success Response (200) - The response typically contains information about the execution of the workflow, potentially including output identifiers or status. ``` -------------------------------- ### Docker Usage for Data Retrieval Source: https://context7.com/ecmwf/cdsapi/llms.txt Instructions on how to use the cdsapi within a Docker container for isolated and reproducible data retrieval. ```APIDOC ## Docker Usage ### Description Utilize the cdsapi within a Docker container to ensure isolated and reproducible data retrieval workflows. This is particularly useful for managing dependencies and ensuring consistent execution environments. ### Request Configuration (`request.json`) ```json { "url": "https://cds.climate.copernicus.eu/api/v2", "uuid": "", "key": "", "variable": "reanalysis-era5-pressure-levels", "options": { "variable": "temperature", "pressure_level": "1000", "product_type": "reanalysis", "date": "2017-12-01/2017-12-31", "time": "12:00", "format": "grib" }, "filename": "output.grib" } ``` ### Docker Command ```bash # Run the Docker container with mounted request and output directories docker run -it --rm \ -v $(pwd)/request.json:/input/request.json \ -v $(pwd):/output \ cdsapi/cdsretrieve ``` ### Explanation - `-v $(pwd)/request.json:/input/request.json`: Mounts your local `request.json` file into the container at `/input/request.json`. - `-v $(pwd):/output`: Mounts your current working directory to `/output` inside the container, where downloaded files will be saved. - `cdsapi/cdsretrieve`: Specifies the Docker image to use. ``` -------------------------------- ### Client.remote() Source: https://context7.com/ecmwf/cdsapi/llms.txt Creates a Result object from a remote URL for downloading files using the CDS infrastructure. ```APIDOC ## Client.remote() ### Description Creates a Result object from a remote URL, enabling the use of cdsapi's download infrastructure for external files. ### Method `client.remote(url)` ### Endpoint N/A (Internal client method) ### Parameters #### Path Parameters - **url** (string) - The URL of the remote file to be accessed. ### Request Example ```python import cdsapi client = cdsapi.Client() # Create a Result object from an external URL result = client.remote("https://example.com/data/climate_data.nc") # Download using cdsapi's robust download mechanism result.download("external_data.nc") ``` ### Response #### Success Response (200) - Returns a Result object that can be used for downloading the remote file. ``` -------------------------------- ### Client.service() Source: https://context7.com/ecmwf/cdsapi/llms.txt Calls a CDS service endpoint for advanced operations beyond simple data retrieval. ```APIDOC ## Client.service() ### Description Calls a CDS service endpoint for advanced operations beyond simple data retrieval, such as using specific tools or mimicking UI behavior. ### Method `client.service(service_name, *args, mimic_ui=False, **kwargs)` ### Endpoint N/A (Internal client method) ### Parameters #### Positional Arguments (*args) - **arg1, arg2, ...** (any) - Positional arguments to be passed to the service. #### Keyword Arguments (**kwargs) - **mimic_ui** (boolean) - If True, mimics the behavior of the CDS User Interface for the service call. - **param1, param2, ...** (any) - Keyword arguments to be passed to the service. ### Request Example ```python import cdsapi client = cdsapi.Client() # Call a service with positional and keyword arguments result = client.service( "tool.toolbox.orchestrator", "arg1", "arg2", param1="value1", param2="value2" ) # Call service mimicking the CDS UI behavior result = client.service( "some.service.name", mimic_ui=True, variable="temperature", format="netcdf" ) ``` ### Response #### Success Response (200) - The structure of the response depends on the specific service called. It can be data, metadata, or a status object. ``` -------------------------------- ### Client.status() Source: https://context7.com/ecmwf/cdsapi/llms.txt Retrieves the current status of the CDS service to check availability. ```APIDOC ## Client.status() ### Description Retrieves the current status of the CDS service, useful for checking service availability before submitting requests. ### Method `client.status()` ### Endpoint N/A (Internal client method) ### Parameters None ### Request Example ```python import cdsapi client = cdsapi.Client() status = client.status() print(f"Service Status: {status}") ``` ### Response #### Success Response (200) - **info** (list of strings) - Information messages about the service status. - **warning** (list of strings) - Warning messages regarding the service. #### Response Example ```json { "info": ["System operational"], "warning": ["Scheduled maintenance on Sunday"] } ``` ``` -------------------------------- ### Custom Logging Callbacks Source: https://context7.com/ecmwf/cdsapi/llms.txt Configure custom functions to handle log messages (info, warning, error, debug) instead of using the default logger. ```APIDOC ## Custom Logging Callbacks ### Description Configure custom callbacks for logging messages instead of relying on the default logger. This allows for flexible handling of log output, such as directing messages to specific files, databases, or custom console formats. ### Callback Functions Define functions for each log level: - `my_info(msg, *args, **kwargs)`: Handles informational messages. - `my_warning(msg, *args, **kwargs)`: Handles warning messages. - `my_error(msg, *args, **kwargs)`: Handles error messages. - `my_debug(msg, *args, **kwargs)`: Handles debug messages. ### Client Initialization Pass your custom callback functions during the `cdsapi.Client` initialization. ### Request Example ```python import cdsapi def my_info(msg, *args, **kwargs): print(f"[INFO] {msg % args if args else msg}") def my_warning(msg, *args, **kwargs): print(f"[WARNING] {msg % args if args else msg}") def my_error(msg, *args, **kwargs): print(f"[ERROR] {msg % args if args else msg}") def my_debug(msg, *args, **kwargs): print(f"[DEBUG] {msg % args if args else msg}") client = cdsapi.Client( info_callback=my_info, warning_callback=my_warning, error_callback=my_error, debug_callback=my_debug, debug=True # Enable debug logging ) # Now all log messages go through custom callbacks result = client.retrieve( "reanalysis-era5-single-levels", {"variable": "2t", "product_type": "reanalysis", "date": "2012-01-01", "time": "00:00"}, "output.grib" ) ``` ### Example Log Output (using custom callbacks) ``` [INFO] Requesting data for reanalysis-era5-single-levels... [DEBUG] Sending request to CDS API... [INFO] Data successfully retrieved and saved to output.grib ``` ``` -------------------------------- ### Result Object Methods Source: https://context7.com/ecmwf/cdsapi/llms.txt Methods available on the Result object for checking status, downloading, and managing retrieved data. ```APIDOC ## Result Object Methods ### Description Methods for interacting with the data retrieval results, including polling for completion, downloading, and accessing metadata. ### Methods #### `result.update()` Refreshes the status of the request from the server. #### `result.reply` Returns a dictionary containing the current status and metadata of the request. #### `result.download(filename)` Downloads the retrieved data to the specified file. - **filename** (string) - The path and name of the file to save the data to. #### `result.check()` Performs a HEAD request to check file availability and retrieve server headers. - **Returns**: A dictionary containing server headers. #### `result.toJSON()` Converts the result metadata into a JSON representation. - **Returns**: A dictionary representing the result in JSON format. #### `result.delete()` Manually deletes the job from the server (if not automatically deleted). ### Request Example ```python import cdsapi client = cdsapi.Client() result = client.retrieve( "reanalysis-era5-single-levels", { "variable": "2t", "product_type": "reanalysis", "date": "2012-12-01", "time": "12:00", } ) # Poll for completion status while True: result.update() reply = result.reply print(f"Request ID: {reply['request_id']}, State: {reply['state']}") if reply["state"] == "completed": break # Add sleep and error handling as needed # Download completed result result.download("output.nc") ``` ### Response Example ```json { "resultType": "url", "contentType": "application/x-netcdf", "contentLength": 1234567, "location": "https://cds.climate.copernicus.eu/api/v2/resources/reanalysis-era5-single-levels/download/abcdef123456" } ``` ``` -------------------------------- ### Poll for Completion and Download Data (Python) Source: https://context7.com/ecmwf/cdsapi/llms.txt This snippet demonstrates how to poll for the completion status of a data request and then download the result. It includes logic for handling different request states (queued, running, completed, failed) and a configurable sleep interval. The download is initiated once the request is completed. ```Python import cdsapi import time # Assume 'result' is an object obtained from client.retrieve() sleep = 30 while True: result.update() # Refresh status from server reply = result.reply print(f"Request ID: {reply['request_id']}, State: {reply['state']}") if reply["state"] == "completed": break elif reply["state"] in ("queued", "running"): print(f"Sleeping {sleep} seconds...") time.sleep(sleep) elif reply["state"] == "failed": error = reply.get("error", {}) raise Exception(f"{error.get('message')}. {error.get('reason')}") # Download completed result result.download("output.nc") ``` -------------------------------- ### Execute CDSAPI Docker Container Source: https://github.com/ecmwf/cdsapi/blob/master/docker/README.md Command to run the Docker container for CDSAPI data retrieval. It mounts the local request JSON file and the current directory for output. Replace `/cdsretrieve` with your actual image name. ```sh docker run -it --rm \ -v $(pwd)/request.json:/input/request.json \ -v $(pwd)/.:/output \ /cdsretrieve ``` -------------------------------- ### Check CDS Service Status (Python) Source: https://context7.com/ecmwf/cdsapi/llms.txt This snippet shows how to use the `client.status()` method to retrieve the current status of the CDS service. This is useful for checking service availability before submitting data requests. The status is returned as a JSON object containing informational messages and potential warnings. ```Python import cdsapi client = cdsapi.Client() # Get CDS service status status = client.status() print(f"Service Status: {status}") # Status returns JSON with info and warnings # Example output: # { # "info": ["System operational"], # "warning": ["Scheduled maintenance on Sunday"] # } ``` -------------------------------- ### JSON Request for CDSAPI Data Retrieval Source: https://github.com/ecmwf/cdsapi/blob/master/docker/README.md Defines the structure of a JSON file used to specify data retrieval parameters for the ECMWF CDSAPI. It includes API endpoint details, user credentials, variable selection, and output filename. ```json { "url": "https://cds.climate.copernicus.eu/api/v2", "uuid": "", "key": "", "variable": "reanalysis-era5-pressure-levels", "options": { "variable": "temperature", "pressure_level": "1000", "product_type": "reanalysis", "date": "2017-12-01/2017-12-31", "time": "12:00", "format": "grib" }, "filename":"test.grib" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.