Darksky官方提供的接口返回的json数据一目了然。
点击向下的那个箭头还可以将下面的内容收缩起来。
我试着自己进行取数,非常容易就取到了。
import urllib2 import json req = urllib2.Request('https://api.darksky.net/forecast/4731c5bca1bc15e6f0738a8d0bc13665/37.8267,-122.4233') response = urllib2.urlopen(req) f = json.loads(response.read()) print f['currently']['summary'] print f['currently']['icon']
另外,已经有人开发了API Libraries,利用这个取数就更方便了,现在python版本的有:
- Python 2 Wrapper Library by Ze'ev Gilovitz
- Python 2 Wrapper Library by David Ervideira
- Python 3 Wrapper Library by Angel Hernandez III
ForcastIO Python 3的使用举例
1、安装ForcastIO Python 3
下载ForcastIO Python 3,解压缩到Anaconda的安装目录下面,然后进入这个目录,执行python setup.py install命令安装。
2、使用ForcastIO Python 3
新建一个py文件,输入以下代码:
from forecastiopy import * Lisbon = [38.7252993, -9.1500364] fio = ForecastIO.ForecastIO('Your API Key', latitude=Lisbon[0], longitude=Lisbon[1]) current = FIOCurrently.FIOCurrently(fio) print('Temperature:', current.temperature) print('Precipitation Probability:', current.precipProbability)
3、获得未来几天的天气
from forecastiopy import * apikey = 'Your API Key' Lisbon = [38.7252993, -9.1500364] fio = ForecastIO.ForecastIO(apikey, units=ForecastIO.ForecastIO.UNITS_SI, lang=ForecastIO.ForecastIO.LANG_ENGLISH, latitude=Lisbon[0], longitude=Lisbon[1]) print('Latitude', fio.latitude, 'Longitude', fio.longitude) print('Timezone', fio.timezone, 'Offset', fio.offset) print(fio.get_url()) # You might want to see the request url if fio.has_daily() is True: daily = FIODaily.FIODaily(fio) print('Daily') print('Summary:', daily.summary) print('Icon:', daily.icon) for day in range(0, daily.days()): print('Day', day+1) for item in daily.get_day(day).keys(): print(item + ' : ' + str(daily.get_day(day)[item])) # Or access attributes directly for a given minute. # daily.day_7_time would also work print(daily.day_5_time) else: print('No Daily data')
4、呈现在网页中
在views.py中加入以下代码:
from forecastiopy import *
将about_me函数改成如下形式(不知是什么原因,之前一直没有显示,加上了x = fio.timezone这句才显示)
def about_me(request) : apikey = '4731c5bca1bc15e6f0738a8d0bc13665' Lisbon = [38.7252993, -9.1500364] fio = ForecastIO.ForecastIO(apikey, units=ForecastIO.ForecastIO.UNITS_SI, lang=ForecastIO.ForecastIO.LANG_ENGLISH, latitude=Lisbon[0], longitude=Lisbon[1]) x = fio.timezone y = fio.get_url() return render(request, 'aboutme.html',{'x':x,'y':y})