Source code for nowcast.workers.download_weather

# Copyright 2016-2019 Doug Latornell, 43ravens
#
# 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.
"""GoMSS NEMO nowcast weather model products download worker.

Download the netCDF files from the Environment Canada GEM 2.5km HRDPS
research model forecast produced by Luc Fillion's group for a specified date;
(defaults to today).
"""
import logging
import os
from pathlib import Path

import arrow
import requests

from nemo_nowcast import get_web_data, NowcastWorker

NAME = "download_weather"
logger = logging.getLogger(NAME)


[docs]def main(): """Set up and run the worker. For command-line usage see: :command:`python -m nowcast.workers.download_weather --help` """ worker = NowcastWorker(NAME, description=__doc__) worker.init_cli() worker.cli.add_date_option( "--forecast-date", default=arrow.now().floor("day"), help="Date for which to download the weather forecast.", ) worker.run(download_weather, success, failure)
def success(parsed_args): ymd = parsed_args.forecast_date.format("YYYY-MM-DD") logger.info( f"{ymd} weather forecast files downloads complete", extra={"forecast_date": ymd} ) msg_type = "success" return msg_type def failure(parsed_args): ymd = parsed_args.forecast_date.format("YYYY-MM-DD") logger.critical( f"{ymd} weather forecast download failed", extra={"forecast_date": ymd} ) msg_type = "failure" return msg_type def download_weather(parsed_args, config, *args): ymd = parsed_args.forecast_date.format("YYYY-MM-DD") logger.info( f"downloading hourly forecast .nc.gz files for {ymd}", extra={"forecast_date": ymd}, ) url = config["weather"]["download"]["url"] dest_dir = Path(config["weather"]["download"]["dest dir"]) forecast_hrs = config["weather"]["download"]["forecast hrs"] filename_tmpl = config["weather"]["download"]["file template"] with requests.Session() as session: for hr in range(forecast_hrs): filename = filename_tmpl.format( yyyymmdd=parsed_args.forecast_date.format("YYYYMMDD"), hhh=f"{hr:03d}" ) _get_file(url, filename, dest_dir, session) checklist = {"forecast date": ymd} return checklist def _get_file(url, filename, dest_dir, session): filepath = dest_dir / filename file_url = os.path.join(url, filename) get_web_data(file_url, NAME, filepath, session) size = filepath.stat().st_size logger.debug( f"downloaded {size} bytes from {file_url}", extra={"url": file_url, "dest_dir": dest_dir}, ) if __name__ == "__main__": main() # pragma: no cover