Advertisement
Guest User

Untitled

a guest
Aug 15th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import requests
  4.  
  5. API_ROOT = 'https://www.metaweather.com'
  6. API_LOCATION = '/api/location/search/?query='
  7. API_WEATHER = '/api/location/' # + woeid
  8.  
  9. def fetch_location(query):
  10. return requests.get(API_ROOT + API_LOCATION + query).json()
  11.  
  12. def fetch_weather(woeid):
  13. return requests.get(API_ROOT + API_WEATHER + str(woeid)).json()
  14.  
  15. def disambiguate_locations(locations):
  16. print("Ambiguous location! Did you mean:")
  17. for loc in locations:
  18. print(f"\t* {loc['title']}")
  19.  
  20. def display_weather(weather):
  21. print(f"Weather for {weather['title']}:")
  22. for entry in weather['consolidated_weather']:
  23. date = entry['applicable_date']
  24. high = entry['max_temp']
  25. low = entry['min_temp']
  26. state = entry['weather_state_name']
  27. print(f"{date}\t{state}\thigh {high:2.1f}°C\tlow {low:2.1f}°C")
  28.  
  29. def weather_dialog():
  30. try:
  31. where = ''
  32. while not where:
  33. where = input("Where in the world are you? ")
  34. locations = fetch_location(where)
  35. if len(locations) == 0:
  36. print("I don't know where that is.")
  37. elif len(locations) > 1:
  38. disambiguate_locations(locations)
  39. else:
  40. woeid = locations[0]['woeid']
  41. display_weather(fetch_weather(woeid))
  42. except requests.exceptions.ConnectionError:
  43. print("Couldn't connect to server! Is the network up?")
  44.  
  45. if __name__ == '__main__':
  46. while True:
  47. weather_dialog()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement