Skip to content
This repository has been archived by the owner on Sep 5, 2023. It is now read-only.

add destination weather api #20

Merged
merged 7 commits into from
Sep 6, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions docs/notebooks/destination_weather.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"source": [
"import os\n",
"os.environ[\"LS_API_KEY\"] = \"MY-API-KEY\" # replace your API key here."
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 3,
"source": [
"import os\n",
"\n",
"from here_location_services import LS\n",
"from here_map_widget import Map, MarkerCluster, ObjectLayer\n",
"from here_location_services.config.dest_weather_config import DEST_WEATHER_PRODUCT\n",
"\n",
"\n",
"LS_API_KEY = os.environ.get(\"LS_API_KEY\")\n",
"ls = LS(api_key=LS_API_KEY)\n",
"\n",
"result1 = ls.get_dest_weather(\n",
" at=[19.1503, 72.8530],\n",
" products=[DEST_WEATHER_PRODUCT.observation]\n",
")\n",
"\n",
"results = []\n",
"m = Map(\n",
" api_key=LS_API_KEY,\n",
" center=[19.1621, 73.0008],\n",
" zoom=7,\n",
")\n",
"for observation in result1.places[0][\"observations\"]:\n",
" results.append(\n",
" dict(\n",
" lat=observation[\"place\"][\"location\"][\"lat\"],\n",
" lng=observation[\"place\"][\"location\"][\"lng\"],\n",
" data=observation[\"description\"] + \" \" + str(observation[\"temperature\"]) + \"C\",\n",
" )\n",
" )\n",
"\n",
"provider = MarkerCluster(data_points=results, show_bubble=True)\n",
"layer = ObjectLayer(provider=provider)\n",
"m.add_layer(layer)\n",
"m"
],
"outputs": [
sackh marked this conversation as resolved.
Show resolved Hide resolved
{
"output_type": "display_data",
"data": {
"text/plain": [
"Map(api_key='TKURWbpJHcbzmWMrmTZwGAdSTLrX8WY1oddj4S4U-EM', basemap=None, center=[19.1621, 73.0008], layers=(Ob…"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "91639eb7343842f1a4feefac3738ab95"
}
},
"metadata": {}
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [],
"outputs": [],
"metadata": {}
}
],
"metadata": {
"orig_nbformat": 4,
"language_info": {
"name": "python",
"version": "3.9.6",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3.9.6 64-bit"
},
"interpreter": {
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
58 changes: 58 additions & 0 deletions docs/source/dest_weather.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
Destination Weather
====================
`Destination Weather API <https://platform.here.com/services/details/hrn:here:service::olp-here:destination-weather-3/overview>`_ provides weather forecasts and reports on current weather conditions. It also provides information on severe weather alerts along a specified route or a single car location.

Example
-------

.. jupyter-execute::

import os
from here_location_services import LS
from here_map_widget import Map, MarkerCluster, ObjectLayer
from here_location_services.config.dest_weather_config import DEST_WEATHER_PRODUCT


LS_API_KEY = os.environ.get("LS_API_KEY")
ls = LS(api_key=LS_API_KEY)

result1 = ls.get_dest_weather(
at=[19.1503, 72.8530],
products=[DEST_WEATHER_PRODUCT.observation]
)

results = []
m = Map(
api_key=LS_API_KEY,
center=[19.1621, 73.0008],
zoom=7,
)
for observation in result1.places[0]["observations"]:
results.append(
dict(
lat=observation["place"]["location"]["lat"],
lng=observation["place"]["location"]["lng"],
data=observation["description"] + " " + str(observation["temperature"]) + "C",
)
)

provider = MarkerCluster(data_points=results, show_bubble=True)
layer = ObjectLayer(provider=provider)
m.add_layer(layer)
m

Attributes
----------

==================== =============================================================================================================== ===
Attribute Type Doc
==================== =============================================================================================================== ===
products list of :class:`DestWeatherProduct <here_location_services.config.dest_weather_config.DestWeatherProduct>` List of strings identifying the type of report to obtain.
at list optional A list of ``latitude`` and ``longitude`` specifying the area covered by the weather report.
query str optional Free text query. Examples: "125, Berliner, berlin", "Beacon, Boston"
zipcode str optional ZIP code of the location. This parameter is supported only for locations in the United States of America.
hourly_date :func:`datetime.datetime` optional Date for which hourly forecasts are to be retrieved.
one_observation bool optional Boolean, if set to true, the response only includes the closest location. Only available when the `product` parameter is set to `DEST_WEATHER_PRODUCT.observation`.
language str optional Defines the language used in the descriptions in the response.
units :class:`DestWeatherUnits <here_location_services.config.dest_weather_config.DestWeatherUnits>` optional Defines whether units or imperial units are used in the response.
==================== =============================================================================================================== ===
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
here\_location\_services.config.dest\_weather\_config module
============================================================

.. automodule:: here_location_services.config.dest_weather_config
:members:
:undoc-members:
:show-inheritance:
:private-members:
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
here\_location\_services.destination\_weather\_api module
=========================================================

.. automodule:: here_location_services.destination_weather_api
:members:
:undoc-members:
:show-inheritance:
:private-members:
1 change: 1 addition & 0 deletions docs/source/here_location_services.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ Submodules
here_location_services.routing_api.rst
here_location_services.utils
here_location_services.platform
here_location_services.destination_weather_api
6 changes: 6 additions & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ A Python client for `HERE Location Services`_.
Routing <routing>
Matrix Routing <matrix_routing>

.. toctree::
:maxdepth: 1
:caption: Destination Weather

Destination Weather <dest_weather>

.. toctree::
:maxdepth: 1
:caption: Reference Guide
Expand Down
68 changes: 68 additions & 0 deletions here_location_services/config/dest_weather_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Copyright (C) 2019-2021 HERE Europe B.V.
# SPDX-License-Identifier: Apache-2.0

"""This module defines all the configs which will be required as inputs to
Destination Weather API."""

from .base_config import Bunch


class DestWeatherProduct(Bunch):
"""A class to define constant attributes for ``product`` parameter identifying the
type of report to obtain.

``observation``:
current weather conditions from the eight closest locations to the specified location

``forecast_7days``:
morning, afternoon, evening and night weather forecasts for the next seven days.

``forecast_7days_simple``:
daily weather forecasts for the next seven days

``forecast_hourly``:
hourly weather forecasts for the next seven days

``alerts``:
forecasted weather alerts for the next 24 hours

``nws_alerts``:
all active watches and warnings for the US and Canada
"""


product = {
"observation": "observation",
"forecast7days": "forecast7days",
"forecast7daysSimple": "forecast7daysSimple",
"forecastHourly": "forecastHourly",
"alerts": "alerts",
"nwsAlerts": "nwsAlerts",
}

#: Use this config for ``products``` of Destination Weather API.
#: Example: for ``forecastHourly`` product use ``DEST_WEATHER_PRODUCT.forecastHourly``.
DEST_WEATHER_PRODUCT = DestWeatherProduct(**product)


class DestWeatherUnits(Bunch):
"""A class to define constant attributes for ``units`` parameter identifying
units of measurement used.

``metric``:
Follow metric system of measurements. Default.

``imperial``:
Follow imperial system of measurements

"""


units = {
"metric": "metric",
"imperial": "imperial",
}

#: Use this config for ``units``` of Destination Weather API.
#: Example: for ``metric`` units use ``DEST_WEATHER_UNITS.metric``.
DEST_WEATHER_UNITS = DestWeatherUnits(**units)
85 changes: 85 additions & 0 deletions here_location_services/destination_weather_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Copyright (C) 2019-2021 HERE Europe B.V.
# SPDX-License-Identifier: Apache-2.0

"""This module contains classes for accessing `HERE Destination Weather API <https://developer.here.com/documentation/destination-weather/dev_guide/topics/overview.html>`_.
""" # noqa E501

from datetime import datetime
from typing import Dict, List, Optional

from here_location_services.platform.auth import Auth

from .apis import Api
from .exceptions import ApiError


class DestinationWeatherApi(Api):
"""A class for accessing HERE routing APIs."""

def __init__(
self,
api_key: Optional[str] = None,
auth: Optional[Auth] = None,
proxies: Optional[dict] = None,
country: str = "row",
):
super().__init__(api_key, auth=auth, proxies=proxies, country=country)
self._base_url = f"https://weather.{self._get_url_string()}"

def get_dest_weather(
self,
products: List[str],
at: Optional[List] = None,
query: Optional[str] = None,
zipcode: Optional[str] = None,
hourly_date: Optional[datetime] = None,
sackh marked this conversation as resolved.
Show resolved Hide resolved
one_observation: Optional[bool] = None,
language: Optional[str] = None,
units: Optional[str] = None,
):
"""Retrieves weather reports, weather forecasts, severe weather alerts and moon and sun rise and set information.

See further information `Here Destination Weather API <https://developer.here.com/documentation/destination-weather/dev_guide/topics/overview.html>_`.

:param products: List of :class:`DestWeatherProduct` identifying the type of
report to obtain.
:param at: A list of ``latitude`` and ``longitude`` specifying the area covered
by the weather report.
:param query: Free text query. Examples: "125, Berliner, berlin", "Beacon, Boston"
:param zipcode: ZIP code of the location. This parameter is supported only for locations in
the United States of America.
:param hourly_date: Date for which hourly forecasts are to be retrieved.
:param one_observation: Boolean, if set to true, the response only includes the closest
location. Only available when the `product` parameter is set to
`DEST_WEATHER_PRODUCT.observation`.
:param language: Defines the language used in the descriptions in the response.
:param units: Defines whether units or imperial units are used in the response.
:return: :class:`requests.Response` object.
:raises ApiError: If ``status_code`` of API response is not 200.
""" # noqa E501

path = "v3/report"
url = f"{self._base_url}/{path}"
params: Dict[str, str] = {
"products": ",".join([str(i) for i in products]),
}
if at:
params["location"] = ",".join([str(i) for i in at])
if query:
params["q"] = query
if zipcode:
params["zipCode"] = zipcode
if hourly_date:
params["hourlyDate"] = hourly_date.strftime("%Y-%m-%dT%H:%M:%S")
sackh marked this conversation as resolved.
Show resolved Hide resolved
if one_observation:
params["oneObservation"] = "true" if one_observation else "false"
if language:
params["lang"] = language
if units:
params["units"] = units

resp = self.get(url, params=params, proxies=self.proxies)
if resp.status_code == 200:
return resp
else:
raise ApiError(resp)
Loading