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:
flask
framework.pip install flask
Note: Never directly use API keys in the code, use them as environment variables for security purposes.
Flask
, os
, and requests
.from flask import Flask
import os, requests
app = Flask(__name__)
@app.route('/', methods =['GET'])
def home():
GET
request to openweathermap
API.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)
JSON
.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 the html_data
.
Provide a port and other parameters to your application.
if __name__ == "__main__":
app.run(port = 8000,debug=True)
python app.py
//or
flask run
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)