Home >  > Darksky API之Python开发

Darksky API之Python开发

0

Darksky官方提供的接口返回的json数据一目了然。

Snap18203

点击向下的那个箭头还可以将下面的内容收缩起来。

我试着自己进行取数,非常容易就取到了。

1import urllib2
2import json
3 
5response = urllib2.urlopen(req)
6f = json.loads(response.read())
7 
8print f['currently']['summary']
9print f['currently']['icon']

效果如下:
Snap18205

另外,已经有人开发了API Libraries,利用这个取数就更方便了,现在python版本的有:

ForcastIO Python 3的使用举例

1、安装ForcastIO Python 3

下载ForcastIO Python 3,解压缩到Anaconda的安装目录下面,然后进入这个目录,执行python setup.py install命令安装。

2、使用ForcastIO Python 3

新建一个py文件,输入以下代码:

1from forecastiopy import *
2 
3Lisbon = [38.7252993, -9.1500364]
4fio = ForecastIO.ForecastIO('Your API Key', latitude=Lisbon[0], longitude=Lisbon[1])
5current = FIOCurrently.FIOCurrently(fio)
6print('Temperature:', current.temperature)
7print('Precipitation Probability:', current.precipProbability)

查看执行结果:
Snap18269

3、获得未来几天的天气

1from forecastiopy import *
2 
3apikey = 'Your API Key'
4 
5Lisbon = [38.7252993, -9.1500364]
6 
7fio = ForecastIO.ForecastIO(apikey,
8                            units=ForecastIO.ForecastIO.UNITS_SI,
9                            lang=ForecastIO.ForecastIO.LANG_ENGLISH,
10                            latitude=Lisbon[0], longitude=Lisbon[1])
11 
12print('Latitude', fio.latitude, 'Longitude', fio.longitude)
13print('Timezone', fio.timezone, 'Offset', fio.offset)
14print(fio.get_url()) # You might want to see the request url
15 
16if fio.has_daily() is True:
17    daily = FIODaily.FIODaily(fio)
18    print('Daily')
19    print('Summary:', daily.summary)
20    print('Icon:', daily.icon)
21 
22    for day in range(0, daily.days()):
23        print('Day', day+1)
24        for item in daily.get_day(day).keys():
25            print(item + ' : ' + str(daily.get_day(day)[item]))
26        # Or access attributes directly for a given minute.
27        # daily.day_7_time would also work
28        print(daily.day_5_time)
29else:
30    print('No Daily data')

运行结果
Snap18271

4、呈现在网页中

在views.py中加入以下代码:

1from forecastiopy import *

将about_me函数改成如下形式(不知是什么原因,之前一直没有显示,加上了x = fio.timezone这句才显示)

1def about_me(request) :
2    apikey = '4731c5bca1bc15e6f0738a8d0bc13665'
3 
4    Lisbon = [38.7252993, -9.1500364]
5 
6    fio = ForecastIO.ForecastIO(apikey,
7                                units=ForecastIO.ForecastIO.UNITS_SI,
8                                lang=ForecastIO.ForecastIO.LANG_ENGLISH,
9                                latitude=Lisbon[0], longitude=Lisbon[1])
10    x = fio.timezone
11    y = fio.get_url()
12    return render(request, 'aboutme.html',{'x':x,'y':y})

然后再修改aboutme.html模板文件
Snap18276

最终成果图:
Snap18277

暧昧帖

本文暂无标签

发表评论

*

*