GAE上有一个cron jobs的功能,类似于Linux下的crontab,可以实现在指定规则的时间里去运行程序。利用这个功能和飞信的短信功能就完成一些简单的小应用,比如天气预报,服务器监控,股票大盘实时行情提醒等等。
拿服务器监控来说,我们先注册一个GAE账户,然后创建一个Application,下载一份GAE 的SDK,接下来就写代码了。
(以上过程请自行google之)
monitor.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#MIT License
#By : cocobear.cn@gmail.com
#
from google.appengine.api import urlfetch
from PyFetion import *
def get():
print('<html><body>')
url = 'http://61.236.244.162'
result = urlfetch.fetch(url)
if result.status_code == 200:
print('OK')
else:
fetion = PyFetion('136xxxx','123456','HTTP')
i = 0
while True:
try:
fetion.login(FetionOnline)
fetion.send_sms('服务器掉了!')
fetion.logout()
except:
if i > 5:
break
continue
print('</body></html>')
if __name__ == '__main__':
get()
很简单的代码,使用GAE的函数urlfetch.fetch来访问这个地址,如果失败调用PyFetion来发短信给自己做通知。
app.yaml:
application: pythoning
version: 1
runtime: python
api_version: 1
handlers:
- url: /console/.*
script: $PYTHON_LIB/google/appengine/ext/admin
login: admin
- url: /monitor
script: monitor.py
- url: /
static_files: index.html
upload: index.html
这里指定url映射的规则,访问pythoning.appspot.com/monitor就会执行monitor.py脚本。application需要填写你申请GAE应用时的名称,也就是这个二级域名pythoning,version:当前代码的版本。
index.html:
首页你可以做别的事,比如放个人主页,然后把自己域名指过来。
cron.yaml:
cron:
- description: watch http server
url: /monitor
schedule: every 1 minutes
timezone: Asia/Shanghai
关键的一个文件,对monitor这个url进行定时执行,这里是每分钟执行一次; 如果你是写天气预报,就可以写为 7:00 every day,每天早上7点发一次天气预报。
写完这些以后,运行命令:
ls demos/test
app.yaml cron.yaml index.html monitor.py PyFetion.py
python appcfg.py update demos/test
把你的代码提交到GAE服务器上,你可以在GAE的后台Cron Jobs看到:
/monitor
watch http server every 1 minutes (Asia/Shanghai)
2009/12/15 14:06:50 on time Success
在GAE上使用r49版本的PyFetion,请注释掉from select import select,如果只是像上面做提醒的话最后去掉下面的代码(824行):
self.get_personal_info()
if not self.get_contactlist():
d_print("get contactlist error")
return False
self.get("compactlist",self.__uri,self.contactlist.keys())
response = self.send()
code = self.get_code(response)
if code != 200:
return False
#self.get("PGGetGroupList",self.__uri)
#response = self.send()
self.get_offline_msg()
这里是获得了好友列表,然后给这些好友发一个上线的通知,如果你不想每次提醒的时飞信上的好友都看到你上线,那么就去掉这些,也会加快发送短信的速度。更进一步的优化,你可以去掉TCP通信的相关代码。
ok, 发挥你的想象力,play with GAE and PyFetion