pax_global_header00006660000000000000000000000064141757427020014523gustar00rootroot0000000000000052 comment=dd20383585359cc80249826977ff102c3a81deee ecmwf-api-client-1.6.3/000077500000000000000000000000001417574270200146565ustar00rootroot00000000000000ecmwf-api-client-1.6.3/.github/000077500000000000000000000000001417574270200162165ustar00rootroot00000000000000ecmwf-api-client-1.6.3/.github/workflows/000077500000000000000000000000001417574270200202535ustar00rootroot00000000000000ecmwf-api-client-1.6.3/.github/workflows/check-and-publish.yml000066400000000000000000000036261417574270200242660ustar00rootroot00000000000000name: Check and publish on: push: branches: [ master ] pull_request: branches: [ master ] release: types: [created] jobs: checks: strategy: fail-fast: false matrix: platform: [windows-latest, ubuntu-latest, macos-latest] python-version: ["3.6", "3.7", "3.8", "3.9"] name: Python ${{ matrix.python-version }} on ${{ matrix.platform }} runs-on: ${{ matrix.platform }} timeout-minutes: 20 steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Tokens shell: python env: ECMWFAPIRC: ${{ secrets.ECMWFAPIRC }} run: | import os for n in ('ECMWFAPIRC',): m = os.path.expanduser("~/." + n.lower()) if os.environ[n]: with open(m, "w") as f: print(os.environ[n], file=f) - name: Tests run: | python setup.py develop pip install pytest pytest deploy: if: ${{ github.event_name == 'release' }} name: Upload to Pypi needs: checks runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.8' - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine - name: Build and publish env: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: | python setup.py sdist twine upload dist/* - name: Notify climetlab uses: mvasigh/dispatch-action@main with: token: ${{ secrets.NOTIFY_ECMWFLIBS }} repo: climetlab owner: ecmwf event_type: ecmwf-api-client-updated ecmwf-api-client-1.6.3/.gitignore000066400000000000000000000001301417574270200166400ustar00rootroot00000000000000build dist ecmwf_api_client.egg-info ecmwfapi/__pycache__ *.pyc *.swp ?.* *.grib *.nc ? ecmwf-api-client-1.6.3/LICENSE000066400000000000000000000262001417574270200156630ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2007-2019 European Centre for Medium-Range Weather Forecasts (ECMWF) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ecmwf-api-client-1.6.3/MANIFEST.in000066400000000000000000000000601417574270200164100ustar00rootroot00000000000000include *.py include LICENSE include MANIFEST.inecmwf-api-client-1.6.3/README.md000066400000000000000000000077171417574270200161510ustar00rootroot00000000000000# ecmwf-api-client # Installation Install via pip with: > $ pip install ecmwf-api-client # Configure ## Anonymous access (default, not recommended) Anonymous access is the default type of access, with no configuration needed. However, anonymous access is only available for a limited set of datasets, and comes with a much lower quality of service. For access to all the available datasets, and an improved quality of service, please use registered access (see below). ## Registered access (recommended) * Register with ECMWF at https://apps.ecmwf.int/registration/. * Login at https://apps.ecmwf.int/auth/login/. * Retrieve you API access key at https://api.ecmwf.int/v1/key/. Note that the API access key expires in 1 year. You will receive an email to the registered email address 1 month before the expiration date with the renewal instructions. To check the expiry date of your current key, log into www.ecmwf.int, and go to https://api.ecmwf.int/v1/key/. * Copy and paste the API access key into the file $HOME/.ecmwfapirc (Unix/Linux) or %USERPROFILE%\\.ecmwfapirc (Windows: usually in C:\\Users\\\\\.ecmwfapirc). Your $HOME/.ecmwfapirc (Unix/Linux) or %USERPROFILE%\\.ecmwfapirc (Windows) should look something like this: ``` { "url" : "https://api.ecmwf.int/v1", "key" : "XXXXXXXXXXXXXXXXXXXXXX", "email" : "john.smith@example.com" } ``` * Alternatively, one can use a file of their own liking, and point to it using environment variable `ECMWF_API_RC_FILE`. `ECMWF_API_RC_FILE` should be set to the full path of the given file. This method takes priority of the previous method of using a .ecmwfapirc file. * As yet another option, one can set the API access key values directly in the environment using variables `ECMWF_API_KEY` (key), `ECMWF_API_URL` (url), `ECMWF_API_EMAIL` (email). This method takes priority over the previous method of using environment variable `ECMWF_API_RC_FILE`. # Example You can test this small python script to retrieve TIGGE (https://apps.ecmwf.int/datasets/data/tigge) data. Note that access to TIGGE data requires registered access, and is subject to accepting a licence at https://apps.ecmwf.int/datasets/data/tigge/licence/. ``` #!/usr/bin/env python from ecmwfapi import ECMWFDataServer # To run this example, you need an API key # available from https://api.ecmwf.int/v1/key/ server = ECMWFDataServer() server.retrieve({ 'origin' : "ecmf", 'levtype' : "sfc", 'number' : "1", 'expver' : "prod", 'dataset' : "tigge", 'step' : "0/6/12/18", 'area' : "70/-130/30/-60", 'grid' : "2/2", 'param' : "167", 'time' : "00/12", 'date' : "2014-11-01", 'type' : "pf", 'class' : "ti", 'target' : "tigge_2014-11-01_0012.grib" }) ``` # Logging Logging messages by default are emitted to `stdout` using Python's `print` statement. To change that behaviour, one can define their own logging function and use it like so: ``` import logging from ecmwfapi import ECMWFDataServer logging.basicConfig(level=logging.INFO) def my_logging_function(msg): logging.info(msg) server = ECMWFDataServer(log=my_logging_function) ``` # License Copyright 2019 European Centre for Medium-Range Weather Forecasts (ECMWF) Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at > http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. In applying this licence, ECMWF does not waive the privileges and immunities granted to it by virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. ecmwf-api-client-1.6.3/ecmwfapi/000077500000000000000000000000001417574270200164515ustar00rootroot00000000000000ecmwf-api-client-1.6.3/ecmwfapi/__init__.py000066400000000000000000000011531417574270200205620ustar00rootroot00000000000000"""Python client for ECMWF web services API.""" # # (C) Copyright 2012-2013 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation nor # does it submit to any jurisdiction. # from ecmwfapi import api __all__ = [ "ECMWFDataServer", "ECMWFService", ] __version__ = api.VERSION ECMWFDataServer = api.ECMWFDataServer ECMWFService = api.ECMWFService ecmwf-api-client-1.6.3/ecmwfapi/api.py000077500000000000000000000460571417574270200176130ustar00rootroot00000000000000# # (C) Copyright 2012-2013 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation nor # does it submit to any jurisdiction. # make the python3-like print behave in python 2 from __future__ import print_function import json import os import sys import time import traceback import textwrap from contextlib import closing # python 2 and 3 compatible urllib and httplib imports try: from urllib.parse import urlparse from urllib.parse import urljoin from urllib.error import HTTPError, URLError from urllib.request import ( HTTPRedirectHandler, Request, build_opener, urlopen, addinfourl, ) from http.client import BadStatusLine except ImportError: from urlparse import urlparse from urlparse import urljoin from urllib2 import HTTPError, URLError from urllib2 import HTTPRedirectHandler, Request, build_opener, urlopen, addinfourl from httplib import BadStatusLine try: import ssl except ImportError: sys.exit("Python socket module was not compiled with SSL support. Aborting...") VERSION = "1.6.3" DEFAULT_RCFILE_PATH = "~/.ecmwfapirc" ANONYMOUS_APIKEY_VALUES = ( "anonymous", "https://api.ecmwf.int/v1", "anonymous@ecmwf.int", ) class APIKeyNotFoundError(Exception): pass class APIKeyFetchError(Exception): pass def get_apikey_values_from_environ(): apikey_values = ( os.getenv("ECMWF_API_KEY"), os.getenv("ECMWF_API_URL"), os.getenv("ECMWF_API_EMAIL"), ) if not any(apikey_values): raise APIKeyNotFoundError("ERROR: No API key found in the environment") elif not all(apikey_values): raise APIKeyFetchError("ERROR: Incomplete API key found in the environment") else: return apikey_values def get_apikey_values_from_rcfile(rcfile_path): rcfile_path = os.path.normpath(os.path.expanduser(rcfile_path)) try: with open(rcfile_path) as f: apikey = json.load(f) except FileNotFoundError as e: raise APIKeyNotFoundError(str(e)) except IOError as e: # Failed reading from file raise APIKeyFetchError(str(e)) except ValueError: # JSON decoding failed raise APIKeyFetchError( "ERROR: Missing or malformed API key in '%s'" % rcfile_path ) except Exception as e: # Unexpected error raise APIKeyFetchError(str(e)) else: try: return (apikey["key"], apikey["url"], apikey["email"]) except: raise APIKeyFetchError( "ERROR: Missing or malformed API key in '%s'" % rcfile_path ) def get_apikey_values(): """Get the API key values in Python tuple format either directly from the environment, or from a file. If no API key is found, fall back to anonymous access. The complete workflow is the following: - Step 1: the environment is checked for variables ECMWF_API_KEY, ECMWF_API_URL, ECMWF_API_EMAIL. * If all found, and not empty, return their values in Python tuple format. * If only some found, and not empty, assume an incomplete API key, and raise APIKeyFetchError. * If none found, or found but empty, assume no API key available in the environment, and continue to the next step. - Step 2: the environment is checked for variable ECMWF_API_RC_FILE, meant to point to a user defined API key file. * If found, but pointing to a file not found, raise APIKeyNotFoundError. * If found, and the file it points to exists, but cannot not be read, or contains an invalid API key, raise APIKeyFetchError. * If found, and the file it points to exists, can be read, and contains a valid API key, return the API key in Python tuple format. * If not found, or empty, assume no user provided API key file and continue to the next step. - Step 3: try the default ~/.ecmwfapirc file. * Same as step 2, except for when ~/.ecmwfapirc is not found, where we continue to the next step. - Step 4: No API key found, so fall back to anonymous access. Returns: Pyhon tuple with the API key token, url, and email. Raises: APIKeyFetchError: If an API key is found, but invalid. APIKeyNotFound: When ECMWF_API_RC_FILE is defined, but pointing to a file that does not exist. """ try: return get_apikey_values_from_environ() except APIKeyNotFoundError: env_rcfile_path = os.getenv("ECMWF_API_RC_FILE") if env_rcfile_path: return get_apikey_values_from_rcfile(env_rcfile_path) else: try: return get_apikey_values_from_rcfile(DEFAULT_RCFILE_PATH) except APIKeyNotFoundError: return ANONYMOUS_APIKEY_VALUES class RetryError(Exception): def __init__(self, code, text): self.code = code self.text = text def __str__(self): return "%d %s" % (self.code, self.text) class APIException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def robust(func): def wrapped(self, *args, **kwargs): max_tries = tries = 10 delay = 60 # retry delay last_error = None while tries > 0: try: return func(self, *args, **kwargs) except HTTPError as e: if self.verbose: self.log("WARNING: HTTPError received %s" % e) if e.code < 500 or e.code in (501,): # 501: not implemented raise last_error = e except BadStatusLine as e: if self.verbose: self.log("WARNING: BadStatusLine received %s" % e) last_error = e except URLError as e: if self.verbose: self.log("WARNING: URLError received %s %s" % (e.errno, e)) last_error = e except APIException: raise except RetryError as e: if self.verbose: self.log("WARNING: HTTP received %s" % e.code) self.log(e.text) last_error = e except: if self.verbose: self.log("Unexpected error: %s" % sys.exc_info()[0]) self.log(traceback.format_exc()) raise self.log("Error contacting the WebAPI, retrying in %d seconds ..." % delay) time.sleep(delay) tries -= 1 # if all retries have been exhausted, raise the last exception caught self.log("Could not contact the WebAPI after %d tries, failing !" % max_tries) raise last_error return wrapped def get_api_url(url): parsed_uri = urlparse(url) return "{uri.scheme}://{uri.netloc}/{apiver}/".format( uri=parsed_uri, apiver=parsed_uri.path.split("/")[1] ) class Ignore303(HTTPRedirectHandler): """Handler to automatically follow redirects. Mainly implement when the API moved from http to https. """ def redirect_request(self, req, fp, code, msg, headers, newurl): if code in [301, 302]: # We want the posts to work even if we are redirected try: # Python < 3.4 data = req.get_data() except AttributeError: # Python >= 3.4 data = req.data try: # Python < 3.4 origin_req_host = req.get_origin_req_host() except AttributeError: # Python >= 3.4 origin_req_host = req.origin_req_host return Request( newurl, data=data, headers=req.headers, origin_req_host=origin_req_host, unverifiable=True, ) return None def http_error_303(self, req, fp, code, msg, headers): return addinfourl(fp, headers, req.get_full_url(), code) def no_log(msg): pass def print_with_timestamp(msg): t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("%s %s" % (t, msg)) class Connection(object): def __init__( self, url, email=None, key=None, verbose=False, quiet=False, log=no_log ): self.url = url self.email = email self.key = key self.retry = 5 self.location = None self.done = False self.value = True self.offset = 0 self.verbose = verbose self.quiet = quiet self.log = log self.status = None @robust def call(self, url, payload=None, method="GET"): # Ensure full url url = urljoin(self.url, url) if self.verbose: self.log("Calling method %s on %s" % (method, url)) headers = { "Accept": "application/json", "From": self.email, "X-ECMWF-KEY": self.key, } opener = build_opener(Ignore303) data = None if payload is not None: data = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" url = "%s?offset=%d&limit=500" % (url, self.offset) req = Request(url=url, data=data, headers=headers) if method: req.get_method = lambda: method error = False try: try: res = opener.open(req) except HTTPError as e: # It seems that some version of urllib2 are buggy if e.code <= 299: res = e else: raise except HTTPError as e: if self.verbose: self.log(e) error = True res = e # 429: Too many requests # 502: Proxy Error # 503: Service Temporarily Unavailable if e.code == 429 or e.code >= 500: raise RetryError(e.code, e.read()) self.retry = int(res.headers.get("Retry-After", self.retry)) code = res.code if code in [201, 202]: self.location = urljoin(url, res.headers.get("Location", self.location)) if self.verbose: self.log("Response code: %s" % code) self.log("Response Content-Type: %s" % res.headers.get("Content-Type")) self.log("Response Content-Length: %s" % res.headers.get("Content-Length")) self.log("Response Location: %s" % res.headers.get("Location")) body = res.read().decode("utf-8") res.close() if code in [204]: self.last = None return None else: try: self.last = json.loads(body) except Exception as e: self.last = {"error": "%s: %s" % (e, body)} error = True if self.verbose: self.log("Response content: %s" % json.dumps(self.last, indent=4)) self.status = self.last.get("status", self.status) if self.verbose: self.log("Status %s" % self.status) if "messages" in self.last: for n in self.last["messages"]: if not self.quiet: self.log(n) self.offset += 1 if code == 200 and self.status == "complete": self.value = self.last self.done = True if isinstance(self.value, dict) and "result" in self.value: self.value = self.value["result"] if code in [303]: self.value = self.last self.done = True if "error" in self.last: raise APIException("ecmwf.API error 1: %s" % (self.last["error"],)) if error: raise APIException("ecmwf.API error 2: %s" % (res,)) return self.last def submit(self, url, payload): self.call(url, payload, "POST") def POST(self, url, payload): return self.call(url, payload, "POST") def GET(self, url): return self.call(url, None, "GET") def wait(self): if self.verbose: self.log("Sleeping %s second(s)" % (self.retry)) time.sleep(self.retry) self.call(self.location, None, "GET") def ready(self): return self.done def result(self): return self.value def cleanup(self): try: if self.location: self.call(self.location, None, "DELETE") except: pass class APIRequest(object): def __init__( self, url, service, email=None, key=None, log=no_log, quiet=False, verbose=False, news=True, ): self.url = url self.service = service self.log = log self.quiet = quiet self.verbose = verbose self.connection = Connection( url, email=email, key=key, quiet=quiet, verbose=verbose, log=log ) self.log("ECMWF API python library %s" % (VERSION,)) self.log("ECMWF API at %s" % (self.url,)) user = self.connection.call("%s/%s" % (self.url, "who-am-i")) if os.getenv("GITHUB_ACTION") is None: self.log("Welcome %s" % (user["full_name"] or "user '%s'" % user["uid"],)) general_info = self.connection.call("%s/%s" % (self.url, "info")).get("info") self.show_info(general_info, user["uid"]) service_specific_info = self.connection.call( "%s/%s/%s" % (self.url, self.service, "info") ).get("info") self.show_info(service_specific_info, user["uid"]) if news: try: news = self.connection.call( "%s/%s/%s" % (self.url, self.service, "news") ) for n in news["news"].split("\n"): self.log(n) except: pass def _bytename(self, size): prefix = {"": "K", "K": "M", "M": "G", "G": "T", "T": "P", "P": "E"} l = "" size = size * 1.0 while 1024 < size: l = prefix[l] size = size / 1024 s = "" if size > 1: s = "s" return "%g %sbyte%s" % (size, l, s) @robust def _transfer(self, url, path, size): start = time.time() existing_size = 0 req = Request(url) if os.path.exists(path): mode = "ab" existing_size = os.path.getsize(path) req.add_header("Range", "bytes=%s-" % existing_size) else: mode = "wb" self.log( "Transfering %s into %s" % (self._bytename(size - existing_size), path) ) self.log("From %s" % (url,)) bytes_transferred = 0 with open(path, mode) as f: with closing(urlopen(req)) as http: while True: chunk = http.read(1048576) # 1MB chunks if not chunk: break f.write(chunk) bytes_transferred += len(chunk) end = time.time() if end > start: transfer_rate = bytes_transferred / (end - start) self.log("Transfer rate %s/s" % self._bytename(transfer_rate)) return existing_size + bytes_transferred def execute(self, request, target=None): status = None self.connection.submit("%s/%s/requests" % (self.url, self.service), request) self.log("Request submitted") self.log("Request id: " + self.connection.last.get("name")) if self.connection.status != status: status = self.connection.status self.log("Request is %s" % (status,)) while not self.connection.ready(): if self.connection.status != status: status = self.connection.status self.log("Request is %s" % (status,)) self.connection.wait() if self.connection.status != status: status = self.connection.status self.log("Request is %s" % (status,)) result = self.connection.result() if target: if os.path.exists(target): # Empty the target file, if it already exists, otherwise the # transfer below might be fooled into thinking we're resuming # an interrupted download. open(target, "w").close() size = -1 tries = 0 while size != result["size"] and tries < 10: size = self._transfer( urljoin(self.url, result["href"]), target, result["size"] ) if size != result["size"] and tries < 10: tries += 1 self.log("Transfer interrupted, resuming in 60s...") time.sleep(60) else: break assert size == result["size"] self.connection.cleanup() return result def show_info(self, info, uid): n = 0 if "message" in info: self.log("") n += 1 for m in textwrap.wrap(info["message"]): self.log(m) if uid in info.get("user_messages", {}): self.log("") n += 1 for m in textwrap.wrap(info["user_messages"][uid]): self.log(m) if n: self.log("") class ECMWFDataServer(object): def __init__( self, url=None, key=None, email=None, verbose=False, log=print_with_timestamp ): if url is None or key is None or email is None: key, url, email = get_apikey_values() self.url = url self.key = key self.email = email self.verbose = verbose self.log = log def retrieve(self, req): target = req.get("target") dataset = req.get("dataset") c = APIRequest( self.url, "datasets/%s" % (dataset,), email=self.email, key=self.key, log=self.log, verbose=self.verbose, ) c.execute(req, target) class ECMWFService(object): def __init__( self, service, url=None, key=None, email=None, verbose=False, log=print_with_timestamp, quiet=False, ): if url is None or key is None or email is None: key, url, email = get_apikey_values() self.service = service self.url = url self.key = key self.email = email self.verbose = verbose self.quiet = quiet self.log = log def execute(self, req, target): c = APIRequest( self.url, "services/%s" % (self.service,), email=self.email, key=self.key, log=self.log, verbose=self.verbose, quiet=self.quiet, ) c.execute(req, target) self.log("Done") ecmwf-api-client-1.6.3/example.py000077500000000000000000000016101417574270200166640ustar00rootroot00000000000000#!/usr/bin/env python # # (C) Copyright 2012-2013 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation nor # does it submit to any jurisdiction. # from ecmwfapi import ECMWFDataServer # To run this example, you need an API key # available from https://api.ecmwf.int/v1/key/ server = ECMWFDataServer() server.retrieve( { "dataset": "tigge", "step": "24", "number": "all", "levtype": "sl", "date": "20071001", "time": "00", "origin": "all", "type": "pf", "param": "tp", "area": "70/-130/30/-60", "grid": "2/2", "target": "data.grib", } ) ecmwf-api-client-1.6.3/setup.py000077500000000000000000000030301417574270200163670ustar00rootroot00000000000000#!/usr/bin/env python # # (C) Copyright 2012-2019 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation nor # does it submit to any jurisdiction. # import io import os.path from setuptools import setup, find_packages import ecmwfapi def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return io.open(file_path, encoding="utf-8").read() setup( name="ecmwf-api-client", version=ecmwfapi.__version__, description=ecmwfapi.__doc__, long_description=read("README.md"), author="European Centre for Medium-Range Weather Forecasts (ECMWF)", author_email="software.support@ecmwf.int", license="Apache License Version 2.0", url="https://github.com/ecmwf/ecmwf-api-client", long_description_content_type="text/markdown", packages=find_packages(), zip_safe=True, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Operating System :: OS Independent", ], ) ecmwf-api-client-1.6.3/tests/000077500000000000000000000000001417574270200160205ustar00rootroot00000000000000ecmwf-api-client-1.6.3/tests/test_dataset.py000077500000000000000000000015771417574270200210730ustar00rootroot00000000000000#!/usr/bin/env python3 import ecmwfapi import time import os def test_dataset(): while True: try: c = ecmwfapi.ECMWFDataServer("mars") c.retrieve( { "dataset": "tigge", "step": "24", "levtype": "sl", "date": "20071001", "time": "00", "origin": "ecmf", "type": "cf", "param": "2t", "target": "tigge.grib", } ) assert os.path.getsize("tigge.grib") == 428963 return except ecmwfapi.api.APIException as e: print(e) msg = str(e) if "USER_QUEUED_LIMIT_EXCEEDED" not in msg: raise time.sleep(120) if __name__ == "__main__": test_dataset() ecmwf-api-client-1.6.3/tests/test_mars.py000077500000000000000000000010271417574270200203760ustar00rootroot00000000000000#!/usr/bin/env python3 import ecmwfapi import time import os def test_mars(): while True: try: c = ecmwfapi.ECMWFService("mars") c.execute({"date": "2000-01-01"}, "mars.grib") assert os.path.getsize("mars.grib") == 1238868 return except ecmwfapi.api.APIException as e: print(e) msg = str(e) if "USER_QUEUED_LIMIT_EXCEEDED" not in msg: raise time.sleep(120) if __name__ == "__main__": test_mars()