Last active
January 19, 2020 09:52
-
-
Save sagunsh/eb9d442839e7f886fb44d1b744ecc808 to your computer and use it in GitHub Desktop.
Weather app gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from flask import Flask, request | |
app = Flask(__name__) | |
@app.route('/city') | |
def search_city(): | |
API_KEY = 'your api key' # initialize your key here | |
city = request.args.get('q') # city name passed as argument | |
# call API and convert response into Python dictionary | |
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={API_KEY}' | |
response = requests.get(url).json() | |
# error like unknown city name, inavalid api key | |
if response.get('cod') != 200: | |
message = response.get('message', '') | |
return f'Error getting temperature for {city.title()}. Error message = {message}' | |
# get current temperature and convert it into Celsius | |
current_temperature = response.get('main', {}).get('temp') | |
if current_temperature: | |
current_temperature_celsius = round(current_temperature - 273.15, 2) | |
return f'Current temperature of {city.title()} is {current_temperature_celsius} ℃' | |
else: | |
return f'Error getting temperature for {city.title()}' | |
@app.route('/') | |
def index(): | |
return '<h1>Welcome to weather app</h1>' | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment