Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- """
- Test with API Open Weather (current data)
- """
- import requests
- import sys
- import json
- class Weather(object):
- """ CLASS TO GET INFOS FROM OPEN WEATHER """
- def __init__(self, city='Osasco'):
- self.city = city
- self.key = "5b318944fb61cfbae7a2dc89f20b9d5d"
- self.check_current_weather()
- def check_current_weather(self):
- """ CHECK CURRENT WEATHER WITH ALL INFOS """
- try:
- req = requests.get("http://api.openweathermap.org/data/2.5/weather?q=%s&APPID=%s" % (self.city, self.key))
- self.info = json.loads(req.text)
- return self.info
- except Exception as e:
- print(e)
- sys.exit(1)
- def get_name_city(self):
- """ NAME OF CITY """
- try:
- return self.info['name']
- except KeyError:
- print("Cidade não encontrada")
- sys.exit(1)
- def get_country(self):
- """ NAME OF COUNTRY """
- return str(self.info['sys']['country']).encode('utf-8')
- def get_wind_speed(self):
- """ SHOW AS METERS/SEC OR MILES/HOUR (KM/H too) """
- return(self.info['wind']['speed'])
- def get_current_temp(self):
- """ SHOW AS YOU WANT """
- current_temp = self.info['main']['temp']
- return (self.k_to_c(current_temp))
- def get_min_temp(self):
- """ SHOW AS YOU WANT """
- min_temp = self.info['main']['temp_min']
- return (self.k_to_c(min_temp))
- def get_max_temp(self):
- """ SHOW AS YOU WANT """
- max_temp = self.info['main']['temp_max']
- return (self.k_to_c(max_temp))
- def get_humidity(self):
- """ USE % TO SHOW """
- return "%d" % (self.info['main']['humidity'])
- def get_pressure(self):
- """ SHOW AS hPa """
- return "%d" % (self.info['main']['pressure'])
- def verify_rain(self):
- """ OBVIOUS """
- descrip = str(self.info['weather'])
- descrip = descrip.replace('u', '').replace('{', '').replace('}', '')
- if 'rain' in descrip:
- return 'há previsão de chuva'
- else:
- return 'não há previsão de chuva'
- def k_to_c(self, current_temp):
- """ KELVIN TO CELSIUS """
- return round((current_temp - 273.15), 2)
- if __name__ == '__main__':
- if len(sys.argv) > 2:
- if sys.argv[1].startswith('-c'):
- cidade = sys.argv[2]
- clima = Weather(cidade)
- clima = Weather()
- # --------- SHOW ------------
- print("Na cidade de {} - ({}) está {}°C (max - {}, min - {})\
- , a humidade está em {}%. Pressão em {}hPa e {}."
- .format(clima.get_name_city(), clima.get_country(), clima.get_current_temp(),
- clima.get_max_temp(), clima.get_min_temp(), clima.get_humidity(), clima.get_pressure(), clima.verify_rain()))
Advertisement
Add Comment
Please, Sign In to add comment