python+百度天气API+twilio平台,实现获取城市天气数据,然后发送短信给指定用户

 

获取天气预报

首先获取城市天气数据,通过百度天气预报API接口,可以方便捕获城市的天气信息。
http://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5

直接通过url的方式获取

 

子模块:获取天气数据

import requests
import json

# 利用百度天气预报提供的API接口,获取城市的天气信息
# 输入:url 在url中,程序以token的形式调用API接口
# 返回:字符串文本形式的天气预报
def get_info(url):
	web_data = requests.get(url)
	result = web_data.text
	fin = json.loads(result)
	city = (fin["results"][0]["currentCity"])   #城市
	pm = (fin["results"][0]["pm25"])   #pm2.5
	temperature = (fin["results"][0]["weather_data"][0]["temperature"])   ##今天的温度
	weather = (fin["results"][0]["weather_data"][0]["weather"])   ##今天的天气情况
	wind = (fin["results"][0]["weather_data"][0]["wind"])   ##今天的风向
	return "天气预报::亲爱的用户,{0}今天天气为{1}, 温度{2},风向{3}, PM2.5浓度{4}".format(city,weather,temperature,wind,pm)

 

 

短信通知

国内的短信服务提供商提供的短信接口是收费的,这里使用的Twilio 是国外一个云通信平台,可以为我们提供免费的短信API服务。
https://www.twilio.com/

在Twilio上注册并配置好后台,之后就可以使用程序调取API接口了。

 

调取API接口

先安装Python 库 twilio

[root@localhost ~]# pip install twilio


 

子模块:短信发送

from twilio.rest import Client
# Your Account SID from twilio.com/console
account_sid = ""
# Your Auth Token from twilio.com/console
auth_token  = ""

client = Client(account_sid, auth_token)

#发送短信
#输入:to_number目标号码 ,from_number 使用的号码(twilio提供), sms_text 发送内容
#输出:message id
def send_sms(to_number, from_number, sms_text):
	message = client.messages.create(
	    to = to_number, 
	    from_ = from_number,
	    body = sms_text
	)
	print(message.sid)

 

主模块:获取数据,发送短信

from crawl_info import get_info
from text_sdk import send_sms

to_number=""      #目标号码
from_number=""    #使用号码      

if __name__ == '__main__':
	url = 'http://api.map.baidu.com/telematics/v3/weather?location=蚌埠&output=json&ak=你的ak值'
	text = get_info(url)
	send_sms(to_number,from_number,text) 

 

运行代码

 

最终效果