How to create a weather app using Flask in Python
To create a weather app, we need real-time weather data for different locations. We can store it in a database and serve it, or use a third-party API like openweathermap.
There are several benefits of using a third-party API:
- Provides accurate and real-time data.
- No need for a database.
- Easy to use.
- Pay as you go.
Code
Steps
- To get started, install the
flaskframework.
pip install flask
- Head over to openweathermap and get your API key.
Note: Never directly use API keys in the code, use them as environment variables for security purposes.
- Import
Flask,os, andrequests.
from flask import Flask
import os, requests
- Create an instance of the flask application.
app = Flask(__name__)
- Create a route.
@app.route('/', methods =['GET'])
def home():
- Make a
GETrequest toopenweathermapAPI.
Note: For simplicity, the location name here is hardcoded, but you can create a new HTML form to get a custom location from the user.
construct_url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=" + "your api key goes here"
response = requests.get(construct_url)
- Convert the response to
JSON.
list_of_data = response.json()
- Create an HTML table to display the data.
html_data = f"""
<table border="1">
<tr>
<td>country_code</td>
<td>coordinate</td>
<td>temp</td>
<td>pressure</td>
<td>humidity</td>
</tr>
<tr>
<td>{str(list_of_data['sys']['country'])}</td>
<td>{str(list_of_data['coord']['lon']) + ' '
+ str(list_of_data['coord']['lat'])}</td>
<td>{str(list_of_data['main']['temp']) + 'k'}</td>
<td>{str(list_of_data['main']['pressure'])}</td>
<td>{str(list_of_data['main']['humidity'])}</td>
</tr>
</table>
"""
-
Return the
html_data. -
Provide a port and other parameters to your application.
if __name__ == "__main__":
app.run(port = 8000,debug=True)
- Run application.
python app.py
//or
flask run
Output
from flask import Flaskimport os,requestsapp = Flask(__name__)@app.route('/', methods =['GET'])def home():construct_url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=" + "your api key goes here"response = requests.get(construct_url)list_of_data = response.json()html_data = f"""<table border="1"><tr><td>country_code</td><td>coordinate</td><td>temp</td><td>pressure</td><td>humidity</td></tr><tr><td>{str(list_of_data['sys']['country'])}</td><td>{str(list_of_data['coord']['lon']) + ' '+ str(list_of_data['coord']['lat'])}</td><td>{str(list_of_data['main']['temp']) + 'k'}</td><td>{str(list_of_data['main']['pressure'])}</td><td>{str(list_of_data['main']['humidity'])}</td></tr></table>"""return html_dataif __name__ == "__main__":app.run(port = 8000,debug=True)