├── .gitignore ├── LICENSE ├── Procfile ├── README.md ├── app.py ├── lib ├── __init__.py ├── apiutil.py ├── dailyforecast.py ├── severeweatherpowerdisruptionindex.py ├── tropicalforecastprojectedpath.py ├── weatheralertdetails.py └── weatheralertheadlines.py ├── manifest.yml ├── requirements.txt └── runtime.txt /.gitignore: -------------------------------------------------------------------------------- 1 | samples/ 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | # lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # pyenv 78 | .python-version 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # Environments 87 | .env 88 | .venv 89 | env/ 90 | venv/ 91 | ENV/ 92 | env.bak/ 93 | venv.bak/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | 108 | .vscode/ 109 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: python app.py -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) [![Community](https://img.shields.io/badge/Join-Community-blue.svg)](https://developer.ibm.com/callforcode/solutions/projects/get-started/) 2 | 3 | # Weather Company Data API access for IBM Cloud 4 | 5 | This project shows how to build a basic data access application that continuously runs in the background, processing a variety of weather data from the Weather Company Data for IBM REST API endpoints, including severe weather alerts, tropical storm forecasts, and the daily weather almanac to find conditions over time. 6 | 7 | ## Obtain a Weather Company API Key 8 | 9 | If you are participating in the [Call for Code](https://developer.ibm.com/callforcode/solutions/projects/get-started/) Global Challenge, request access to [The Weather Company APIs](https://developer.ibm.com/callforcode/tools/weather/). Registration is free and will be available while the Call for Code Global Challenge is taking place. After you agree to the terms, you will receive your API key. Additional documentation about The Weather Company APIs for Call for Code is available [here](https://developer.ibm.com/blogs/call-for-code-the-weather-company-and-you/). 10 | 11 | ## Getting Started in IBM Cloud 12 | 13 | Deploy this application to IBM Cloud. 14 | 15 | 1. Install and configure the [IBM Cloud Developer Tools](https://cloud.ibm.com/docs/cli) 16 | 17 | 2. Clone this repository 18 | 19 | ``` 20 | $ git clone https://github.com/Call-for-Code/weather-api-python.git 21 | $ cd weather-api-python 22 | ``` 23 | 24 | 3. Deploy the application without starting it 25 | 26 | ``` 27 | $ ibmcloud cf push --no-start 28 | ``` 29 | 30 | 4. Configure your Weather API key `` and start the application 31 | 32 | ``` 33 | $ ibmcloud cf set-env weather-api-python WEATHER_API_KEY 34 | $ ibmcloud cf start weather-api-python 35 | ``` 36 | 37 | ## Getting Started on your local machine 38 | 39 | To run this application on your local machine, first install Python. 40 | 41 | 1. Clone this repository 42 | 43 | ``` 44 | $ git clone https://github.com/Call-for-Code/weather-api-python.git 45 | $ cd weather-api-python 46 | ``` 47 | 48 | 2. Install the dependencies 49 | 50 | ``` 51 | $ pip install -r requirements.txt 52 | ``` 53 | 54 | 3. Set your Weather API key `` when running the application 55 | ``` 56 | $ export WEATHER_API_KEY= 57 | $ python app.py 58 | ``` 59 | 60 | ## Links 61 | 62 | - [Call for Code](https://callforcode.org/) 63 | - [Call for Code - IBM Developer](https://developer.ibm.com/callforcode/) 64 | - [Call for Code: The Weather Company and you](https://developer.ibm.com/callforcode/blogs/call-for-code-the-weather-company-and-you/) 65 | 66 | ## License 67 | 68 | This code is licensed under Apache 2.0. Full license text is available in [LICENSE](https://github.com/Call-for-Code/weather-api-python/tree/master/LICENSE). 69 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import os, requests, time, schedule 2 | 3 | import lib.weatheralertheadlines as alert_headlines 4 | import lib.weatheralertdetails as alert_details 5 | import lib.dailyforecast as daily_forecast 6 | import lib.tropicalforecastprojectedpath as tropical_forecast 7 | import lib.severeweatherpowerdisruptionindex as power_disruption 8 | 9 | from lib.apiutil import request_headers 10 | 11 | def handleFail(err): 12 | # API call failed... 13 | print('Status code: %d' % (err.status_code) ) 14 | 15 | def callWeatherAlertHeadlines(lat, lon): 16 | url, params = alert_headlines.request_options(lat, lon) 17 | headers = request_headers() 18 | 19 | r = requests.get(url, params=params, headers=headers) 20 | if r.status_code == 200: 21 | detailKeys = alert_headlines.handle_response(r.json()) 22 | if detailKeys and len(detailKeys) > 0: 23 | for detailKey in detailKeys: 24 | print('Detail key: '+detailKey) 25 | callWeatherAlertDetails(detailKey) 26 | else: 27 | handleFail(r) 28 | 29 | def callWeatherAlertDetails(detailKey): 30 | url, params = alert_details.request_options(detailKey) 31 | headers = request_headers() 32 | 33 | r = requests.get(url, params=params, headers=headers) 34 | if r.status_code == 200: 35 | alert_details.handle_response(r.json()) 36 | else: 37 | handleFail(r) 38 | 39 | def callTropicalForecastProjectedPath(basin='AL', units='m', nautical=True, source='all'): 40 | url, params = tropical_forecast.request_options(basin, units, nautical, source) 41 | headers = request_headers() 42 | 43 | r = requests.get(url, params=params, headers=headers) 44 | if r.status_code == 200: 45 | tropical_forecast.handle_response(r.json()) 46 | else: 47 | handleFail(r) 48 | 49 | def callDailyForecast(lat, lon, units = 'm'): 50 | url, params = daily_forecast.request_options(lat, lon) 51 | headers = request_headers() 52 | 53 | r = requests.get(url, params=params, headers=headers) 54 | if r.status_code == 200: 55 | daily_forecast.handle_response(r.json()) 56 | else: 57 | handleFail(r) 58 | 59 | def callSevereWeatherPowerDisruption(lat, lon): 60 | url, params = power_disruption.request_options(lat, lon) 61 | headers =request_headers() 62 | 63 | r = requests.get(url, params=params, headers=headers) 64 | if r.status_code == 200: 65 | power_disruption.handle_response(r.json()) 66 | else: 67 | handleFail(r) 68 | 69 | 70 | loc = { 71 | 'boston': { 'lat': '42.3600', 'lon': '-71.06536' }, # Boston, MA, United States 72 | 'raleigh': { 'lat': '35.843686', 'lon': '-78.78548' }, # Raleigh, NC, United States 73 | 'losangeles': { 'lat': '34.040873', 'lon': '-118.482745' }, # Los Angeles, CA, United States 74 | 'lakecity': { 'lat': '44.4494119', 'lon': '-92.2668435' }, # Lake CIty, MN, United States 75 | 'newyork': { 'lat': '40.742089', 'lon': '-73.987908' }, # New York, NY, United States 76 | 'hawaii': { 'lat': '33.40', 'lon': '-83.42' }, # Hawaii, United States 77 | 'puntacana': { 'lat': '18.57001', 'lon': '-68.36907' }, # Punta Cana, Dominican Republic 78 | 'jakarta': { 'lat': '-5.7759349', 'lon': '106.1161341' } # Jakarta, Indonesia 79 | } 80 | 81 | 82 | ######################## 83 | # Make a single API call 84 | ######################## 85 | 86 | callDailyForecast(loc['raleigh']['lat'], loc['raleigh']['lon']) 87 | # callWeatherAlertHeadlines(loc['lakecity']['lat'], loc['lakecity']['lon']) 88 | # callSevereWeatherPowerDisruption(loc['jakarta']['lat'], loc['jakarta']['lon']) 89 | # callTropicalForecastProjectedPath() 90 | # callWeatherAlertDetails('06439e88-320a-3722-ae90-097484ff2277') 91 | 92 | 93 | ######################## 94 | # Setting up a job to look for weather alert headlines every 10 minutes 95 | ######################## 96 | 97 | def job(): 98 | callWeatherAlertHeadlines(loc['lakecity']['lat'], loc['lakecity']['lon']) 99 | 100 | schedule.every(10).minutes.do(job) 101 | 102 | while True: 103 | schedule.run_pending() 104 | time.sleep(100) 105 | -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Call-for-Code/weather-api-python/99ea49cfdae7db90752edb696fe0c24669a8d01e/lib/__init__.py -------------------------------------------------------------------------------- /lib/apiutil.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | __name__ = 'dailyforecast' 4 | 5 | host = 'https://api.weather.com' 6 | 7 | def default_params(): 8 | return { 9 | 'apiKey': os.environ['WEATHER_API_KEY'], 10 | 'language': 'en-US' 11 | } 12 | 13 | def request_headers(): 14 | return { 15 | 'User-Agent': 'Request-Promise', 16 | 'Accept': 'application/json', 17 | 'Accept-Encoding': 'gzip' 18 | } 19 | -------------------------------------------------------------------------------- /lib/dailyforecast.py: -------------------------------------------------------------------------------- 1 | # Daily Forecast 2 | # 3 | # - https://weather.com/swagger-docs/ui/sun/v1/sunV1DailyForecast.json 4 | # 5 | # The daily forecast API returns the geocode weather forecasts for the current day 6 | # up to the days duration in the API endpoint. The daily forecast product can contain 7 | # multiple days of daily forecasts for each location. Each day of a forecast can 8 | # contain up to (3) “temporal segments” meaning three separate forecasts. For any 9 | # given forecast day we offer day, night, and a 24-hour forecast (daily summary). 10 | # 11 | # Base URL: api.weather.com/v1 12 | # Endpoint: /geocode/{latitude}/{longitude}/forecast/daily/{days}day.json 13 | 14 | __name__ = 'dailyforecast' 15 | 16 | from lib.apiutil import host, default_params 17 | 18 | def request_options (lat, lon, days = 3, units = 'm'): 19 | d = days if days in [3, 5, 7, 10, 15] else 3 20 | u = units if units in ['e', 'm', 'h', 's'] else 'm' 21 | 22 | url = host + '/v1/geocode/{lat}/{lon}/forecast/daily/{days}day.json'.format(lat=lat, lon=lon, days=d) 23 | 24 | params = default_params() 25 | params['units'] = u 26 | 27 | return url, params 28 | 29 | def handle_response (res): 30 | if res and res['forecasts']: 31 | forecasts = res['forecasts'] 32 | print('daily-forecast: returned {}-day forecast'.format(len(forecasts))) 33 | 34 | # each entry in the forecasts array corresponds to a daily forecast 35 | for index, daily in enumerate(forecasts): 36 | print('daily-forecast: day {} - High of {}, Low of {}'.format(index, daily['max_temp'], daily['min_temp'])) 37 | print('daily-forecast: day {} - {}'.format(index, daily['narrative'])) 38 | 39 | # additional entries include (but not limited to): 40 | # lunar_phase, sunrise, day['uv_index'], night['wdir'], etc 41 | else: 42 | print('daily-forecast: no daily forecast returned') 43 | 44 | 45 | # API = /v3/wx/forecast/daily/{days}day 46 | # API = '/v3/wx/forecast/daily/10day' 47 | # API = '/v3/wx/forecast/daily/7day' 48 | # API = '/v3/wx/forecast/daily/5day' 49 | # API = '/v3/wx/forecast/daily/3day' 50 | 51 | # def handleResponse(res): 52 | # if res and res['dayOfWeek']: 53 | # days = res['dayOfWeek'] 54 | # print('daily-forecast: returned %d-day forecast' % (len(days))) 55 | 56 | # # each entry in the response object is an array with 57 | # # entries in the array applying to the day of the week 58 | # # (i.e., res['dayOfWeek']) matched by the index 59 | # for index, day in enumerate(days): 60 | # maxtemp = str(res['temperatureMax'][index]) if res['temperatureMax'][index] else 'n/a' 61 | # mintemp = str(res['temperatureMin'][index]) if res['temperatureMin'][index] else 'n/a' 62 | # print ('daily-forecast: %s - High of %s, Low of %s' % (day, maxtemp, mintemp) ) 63 | # print ('daily-forecast: %s - %s' % (day, res['narrative'][index]) ) 64 | 65 | # # additional entries include (but not limited to): 66 | # # moonPhase, sunriseTimeLocal, daypart['precipChance'], daypart['windDirection'], etc 67 | # else: 68 | # print('daily-forecast: daily forecast returned') 69 | 70 | 71 | # def callDailyForecast(lat, lon, units = 'm'): 72 | # url = HOST + lib.dailyforecast.API 73 | # options = defaultParams 74 | # options['qs']['geocode'] = ( '%f,%f' % (lat, lon) ) 75 | # options['qs']['units'] = units 76 | 77 | # r = requests.get( url, params=options['qs'], headers=options['headers'] ) 78 | # if r.status_code == 200: 79 | # lib.dailyforecast.handleResponse( r.json() ) 80 | # else: 81 | # handleFail(r) 82 | 83 | -------------------------------------------------------------------------------- /lib/severeweatherpowerdisruptionindex.py: -------------------------------------------------------------------------------- 1 | # Severe Weather Power Disruption Index 15 Day 2 | # 3 | # - https://weather.com/swagger-docs/ui/sun/v2/SUNv2SevereWeatherPowerDisruptionIndex.json 4 | # 5 | # The Power Disruption index provides indices indicating the potential for power 6 | # disruptions due to weather. 7 | # 8 | # Base URL: api.weather.com/v2 9 | # Endpoint: /indices/powerDisruption/daypart/15day 10 | 11 | __name__ = 'severeweatherpowerdisruptionindex' 12 | 13 | from lib.apiutil import host, default_params 14 | 15 | def request_options (lat, lon): 16 | url = host + '/v2/indices/powerDisruption/daypart/15day' 17 | 18 | params = default_params() 19 | params['geocode'] = '{lat},{lon}'.format(lat=lat, lon=lon) 20 | params['format'] = 'json' 21 | 22 | return url, params 23 | 24 | def handle_response (res): 25 | if res and res['powerDisruptionIndex12hour']: 26 | p = res['powerDisruptionIndex12hour'] 27 | for i, disruptIndex in enumerate(p['powerDisruptionIndex']): 28 | print('severe-weather-power-disruption-index: {}: {}'.format(disruptIndex, p['powerDisruptionCategory'][i])) 29 | else: 30 | print('severe-weather-power-disruption-index: no power distruption info returned') 31 | -------------------------------------------------------------------------------- /lib/tropicalforecastprojectedpath.py: -------------------------------------------------------------------------------- 1 | # Tropical -Forecast - Projected Path 2 | # 3 | # - https://weather.com/swagger-docs/ui/sun/v2/SUNv2TropicalForecastProjectedPathSourceAndBasinOnly.json 4 | # 5 | # The Tropical Forecast - Projected Path API provides the ability query the single 6 | # projected path per active storm. Active storm - any storm that has reported in the 7 | # last 168 hours. One can query by basin or selected source. 8 | # 9 | # Base URL: api.weather.com/v2 10 | # Endpoint: /tropical/projectedpath 11 | 12 | __name__ = 'tropicalforecastprojectedpath' 13 | 14 | from lib.apiutil import host, default_params 15 | 16 | def request_options (basin = 'AL', units = 'm', nautical = True, source = 'all'): 17 | u = units if units in ['e', 'm', 'h', 's'] else 'm' 18 | 19 | url = host + '/v2/tropical/projectedpath' 20 | 21 | params = default_params() 22 | params['units'] = u 23 | params['basin'] = basin 24 | params['nautical'] = 'true' if nautical else 'false' 25 | params['source'] = source 26 | params['format'] = 'json' 27 | 28 | return url, params 29 | 30 | def handle_response (res): 31 | if res and res['advisoryinfo']: 32 | print('tropical-forecast-projected-path: returned {} advisory info'.format(len(res['advisoryinfo']))) 33 | 34 | for storm in res['advisoryinfo']: 35 | # the storm's storm_name, projectedpath, and projectedpath.heading objects are probably of interest 36 | print('tropical-forecast-projected-path: Advisoory for storm "{}" by "{}"'.format(storm['storm_name'], storm['source'])) 37 | print('tropical-forecast-projected-path: {} - {}'.format(storm['storm_name'], storm['projectedpath'])) 38 | else: 39 | print('tropical-forecast-projected-path: No advisory info available') 40 | 41 | -------------------------------------------------------------------------------- /lib/weatheralertdetails.py: -------------------------------------------------------------------------------- 1 | # Weather Alerts Detail 2 | # 3 | # - https://weather.com/swagger-docs/ui/sun/v3/sunV3AlertsWeatherAlertDetail.json 4 | # 5 | # The Weather Alert Details API provides weather watches, warnings, statements and 6 | # advisories issued by the NWS (National Weather Service), Environment Canada and 7 | # MeteoAlarm. These weather alerts can provide crucial life-saving information. 8 | # Weather alerts can be complicated and do not always follow consistent standards, 9 | # format and rules. The Weather Channel (TWC) strives to ensure that the information 10 | # is consistent from all of the different sources but the content is subject to 11 | # change whenever there is an update from the authoritative source. The Weather Alert 12 | # Headlines API returns active weather alert headlines related to Severe 13 | # Thunderstorms, Tornadoes, Earthquakes, Floods, etc . This API also returns 14 | # non-weather alerts such as Child Abduction Emergency and Law Enforcement Warnings. 15 | # The Alert Headlines API also provides a key value found in the attribute to access 16 | # the alert details in the Alert Details API. Your application should first call the 17 | # Weather Alert Headlines API and use the value found in the attribute to request the 18 | # detailed information found in the Weather Alert Details API. 19 | # 20 | # Base URL: api.weather.com/v3 21 | # Endpoint: /alerts/detail 22 | 23 | __name__ = 'weatheralertdetails' 24 | 25 | from lib.apiutil import host, default_params 26 | 27 | def request_options (detail_key): 28 | url = host + '/v3/alerts/detail' 29 | 30 | params = default_params() 31 | params['alertId'] = detail_key 32 | params['format'] = 'json' 33 | 34 | return url, params 35 | 36 | def handle_response (res): 37 | if res and res['alertDetail']: 38 | alert = res['alertDetail'] 39 | # Main thing here that is not in the alert headline is the alert['texts'] array 40 | print('weather-alerts-detail: {}'.format(alert['headlineText'])) 41 | 42 | if alert['texts']: 43 | for text in alert['texts']: 44 | print(text['languageCode']) 45 | print(text['instruction']) 46 | print(text['overview']) 47 | print(text['description']) 48 | else: 49 | print('weather-alerts-detail: No alert text available') 50 | else: 51 | print('weather-alerts-detail: No alert detail available') 52 | -------------------------------------------------------------------------------- /lib/weatheralertheadlines.py: -------------------------------------------------------------------------------- 1 | # Weather Alerts Headlines 2 | # 3 | # - https://weather.com/swagger-docs/ui/sun/v3/sunV3AlertsWeatherAlertsHeadlines.json 4 | # 5 | # The Weather Alert Headlines API provides weather watches, warnings, statements and 6 | # advisories issued by the NWS (National Weather Service), Environment Canada and 7 | # MeteoAlarm. These weather alerts can provide crucial life-saving information. 8 | # Weather alerts can be complicated and do not always follow consistent standards, 9 | # format and rules. The Weather Channel (TWC) strives to ensure that the information 10 | # is consistent from all of the different sources but the content is subject to 11 | # change whenever there is an update from the authoritative source. 12 | # 13 | # The Weather Alert Headline API returns active weather alert headlines related to 14 | # Severe Thunderstorms, Tornadoes, Earthquakes, Floods, etc . This API also returns 15 | # non-weather alerts such as Child Abduction Emergency and Law Enforcement Warnings. 16 | # The Alert Headlines API also provides a key value found in the attribute to access 17 | # the alert details in the Alert Details API. 18 | # 19 | # Base URL: api.weather.com/v3 20 | # Endpoint: /alerts/headlines 21 | 22 | __name__ = 'weatheralertheadlines' 23 | 24 | from lib.apiutil import host, default_params 25 | 26 | def request_options (lat, lon): 27 | url = host + '/v3/alerts/headlines' 28 | 29 | params = default_params() 30 | params['geocode'] = '{lat},{lon}'.format(lat=lat, lon=lon) 31 | params['format'] = 'json' 32 | 33 | return url, params 34 | 35 | def handle_response (res): 36 | details = [] 37 | 38 | if res and res['alerts']: 39 | # loop through alerts 40 | for alert in res['alerts']: 41 | # check fields to decide if this alert is important to you. 42 | print(alert) 43 | 44 | if alert['severityCode'] <= 3 and alert['certaintyCode'] <= 3 and alert['urgencyCode'] <= 3: 45 | details.append(alert['detailKey']) 46 | 47 | print('weather-alert-headlines: returning {} alert(s) meeting threshold out of {} total'.format(len(details), len(res['alerts']))) 48 | else: 49 | print('weather-alert-headlines: No alerts in area') 50 | 51 | # return the detail_key(s) for alerts you deemed important 52 | return details 53 | -------------------------------------------------------------------------------- /manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: weather-api-python 4 | no-route: true 5 | health-check-type: process 6 | command: python app.py 7 | path: . 8 | memory: 256M 9 | instances: 1 10 | env: 11 | WEATHER_API_KEY: 12 | NPM_CONFIG_PRODUCTION: false 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | schedule>=0.5.0 2 | requests>=2.21.0 3 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.6.2 2 | --------------------------------------------------------------------------------