Last active
November 30, 2015 16:24
-
-
Save allieus/4fa672395b75e9e7b907 to your computer and use it in GitHub Desktop.
이수진님 날씨 스크립트 개선
This file contains hidden or 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
# 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