Skip to content

Instantly share code, notes, and snippets.

@allieus
Last active November 30, 2015 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save allieus/4fa672395b75e9e7b907 to your computer and use it in GitHub Desktop.
Save allieus/4fa672395b75e9e7b907 to your computer and use it in GitHub Desktop.
이수진님 날씨 스크립트 개선
# https://github.com/sujinleeme/my-python-journey/blob/master/PR4E/yahoo-weatherAPI.py
import requests
from dateutil.parser import parse as date_parse
from django.utils import timezone
def get_weather(city):
baseurl = 'https://query.yahooapis.com/v1/public/yql'
yql_query = "SELECT * FROM weather.forecast WHERE woeid IN (SELECT woeid FROM geo.places(1) WHERE text='%s')" % city
params = {'q': yql_query, 'format': 'json'}
data = requests.get(baseurl, params=params).json()
if not data['query']['count']:
return 'Not Found'
try:
channel = data['query']['results']['channel']
location = channel['location']
location_summary = ', '.join((location['city'], location['country'], location['region']))
response = []
response.append('Current weather in {location} : {desc} ({temp})'.format(location=location_summary, **parse(channel['item']['condition'])))
for condition in channel['item']['forecast']:
response.append('[{date}] {desc} ({temp})'.format(**parse(condition)))
return '\n'.join(response)
except KeyError:
return 'Not Found'
def parse(condition):
if 'temp' in condition:
temp = '%d°C' % celsius(condition['temp'])
else:
temp = '%d°C ~ %d°C' % (celsius(condition['low']), celsius(condition['high']))
date = date_parse(condition['date'])
return {
'date': '{}-{}-{} {}'.format(date.year, date.month, date.day, date.tzname() or ''),
'desc': condition['text'],
'temp': temp,
}
def celsius(fahrenheit):
'''change Fahrenheit to Celsius'''
return (int(fahrenheit) - 32) * 5/9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment