|
| 1 | +import datetime |
| 2 | +import functools |
| 3 | +import httpx |
| 4 | +from typing import Dict |
| 5 | + |
| 6 | +from app import config |
| 7 | + |
| 8 | + |
| 9 | +# This feature requires an API KEY - get yours free @ www.weatherapi.com |
| 10 | + |
| 11 | +ASTRONOMY_URL = "http://api.weatherapi.com/v1/astronomy.json" |
| 12 | +NO_API_RESPONSE = "No response from server" |
| 13 | + |
| 14 | + |
| 15 | +@functools.lru_cache(maxsize=128, typed=False) |
| 16 | +async def get_data_from_api(formatted_date: str, location: str)\ |
| 17 | + -> Dict[str, int]: |
| 18 | + """ get the relevant astronomical data by calling the "weather api" API. |
| 19 | + Args: |
| 20 | + formatted_date (date) - relevant date. |
| 21 | + location (str) - location name. |
| 22 | + Returns: |
| 23 | + response_json (json dict) including: |
| 24 | + relevant part (data / error) of the JSON returned by the API. |
| 25 | + Success (bool) |
| 26 | + ErrorDescription (str) - error message. |
| 27 | + """ |
| 28 | + input_query_string = {'key': config.ASTRONOMY_API_KEY, 'q': location, |
| 29 | + 'dt': formatted_date} |
| 30 | + output = {} |
| 31 | + try: |
| 32 | + async with httpx.AsyncClient() as client: |
| 33 | + response = await client.get(ASTRONOMY_URL, |
| 34 | + params=input_query_string) |
| 35 | + except httpx.HTTPError: |
| 36 | + output["Success"] = False |
| 37 | + output["ErrorDescription"] = NO_API_RESPONSE |
| 38 | + return output |
| 39 | + if response.status_code != httpx.codes.OK: |
| 40 | + output["Success"] = False |
| 41 | + output["ErrorDescription"] = NO_API_RESPONSE |
| 42 | + return output |
| 43 | + output["Success"] = True |
| 44 | + try: |
| 45 | + output.update(response.json()['location']) |
| 46 | + return output |
| 47 | + except KeyError: |
| 48 | + output["Success"] = False |
| 49 | + output["ErrorDescription"] = response.json()['error']['message'] |
| 50 | + return output |
| 51 | + |
| 52 | + |
| 53 | +async def get_astronomical_data(requested_date: datetime.datetime, |
| 54 | + location: str) -> Dict[str, int]: |
| 55 | + """ get astronomical data (Sun & Moon) for date & location - |
| 56 | + main function. |
| 57 | + Args: |
| 58 | + requested_date (date) - date requested for astronomical data. |
| 59 | + location (str) - location name. |
| 60 | + Returns: dictionary with the following entries: |
| 61 | + Status - success / failure. |
| 62 | + ErrorDescription - error description (relevant only in case of error). |
| 63 | + location - relevant location values(relevant only in case of success). |
| 64 | + name, region, country, lat, lon etc. |
| 65 | + astronomy - relevant astronomy values, all time in local time - |
| 66 | + (relevant only in case of success): |
| 67 | + sunrise, sunset, moonrise, moonset, moon_phase, moon_illumination. |
| 68 | + """ |
| 69 | + formatted_date = requested_date.strftime('%Y-%m-%d') |
| 70 | + return await get_data_from_api(formatted_date, location) |
0 commit comments