This will be and updated version as the old weather API i did use no longer is online.
Will be looking at using a weather API to get data,then make user interface (UI) for those data in Flask.
API
First gone look at API without Flask.
If go to OpenWeatherMap can get a API key for free.
Using Requests to get JSON data needed:
Flask
Code is here weather-app
If look at server side and
So this will be using jinja and pass values to
We see that values get pass inside
Run
Code weather-app
From command line:
From weather-app folder
Will be looking at using a weather API to get data,then make user interface (UI) for those data in Flask.
- Update 24-jun 2018
- Python 3.6.5
- Flask 1.0.2
- OpenWeatherMap API
API
First gone look at API without Flask.
If go to OpenWeatherMap can get a API key for free.
Using Requests to get JSON data needed:
import requests # Call example #http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&APPID=xxxxxxxxxxxxx api_key = 'xxxxxxxxxxxxxxx' city = 'london' celsius = 'metric' url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&units={celsius}&APPID={api_key}' response = requests.get(url).json() # City print(response.get('name')) # Temp print(response['main'].get('temp')) # Description print(response['weather'][0].get('description')) # Wind print(response['wind'].get('speed'))
Output:London
22.89
clear sky
3.6
Flask
Code is here weather-app
If look at server side and
app.py
.So this will be using jinja and pass values to
weather.html
.try: city = response['name'] temp = response['main']['temp'] description = response['weather'][0]['description'] wind = response['wind']['speed'] except KeyError: return redirect(url_for('error')) return render_template('weather.html', city=city, temp=temp, description=description, wind=windLooking at a part of
weather.html
.We see that values get pass inside
{{ city }}
.<div id="weather-city"> <h1>{{ city }}</h1> </div> <hr> <div id="weather-temp"> {{ temp }} °C
Run
Code weather-app
From command line:
pip install Flask git clone https://[email protected]/snippsat/weather-app.gitAdd own API key in xxxxxxxxx.
From weather-app folder
python app.py
:E:\weather-app (master) λ python app.py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 184-514-049 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)In Browser:
http://127.0.0.1:5000/