用GAE+139邮箱收天气预报

小马 posted @ 2010年1月16日 04:43 in 生活代码 with tags code GAE python weather , 5311 阅读

一直想写个这样的程序,可苦于自己对于这个GAE一窍不通……所以一直也没下手写,今天终于写了一个,其实也十分简单,参照了一下网上的一个些用pyfetion收天气的方法

最关键的是这一部分(虽然很短)

monitor.py

#! /usr/bin/python
#coding=utf-8

import re
from google.appengine.api import mail
from google.appengine.api import urlfetch

wap = urlfetch.fetch('http://m.baidu.com/tq?area=%E5%9E%A6%E5%88%A9').content
Tomorrow = re.findall(r'明\:.*?<',wap)[0][:-1]

mail.send_mail(sender="******@gmail.com", to="******@139.com", subject="Weather", body=Tomorrow)

最初,因为不了解gae的详细用法,先写了一个通用版

 

#! /usr/bin/python

import urllib,re
import email,smtplib,time

wap = urllib.urlopen('http://m.baidu.com/tq?area=%E5%9E%A6%E5%88%A9').read().decode('utf-8') #网页视情况而定
Tomorrow = re.findall(r'明\:.*?<'.decode('gbk'),wap)[0][:-1]

msg = email.Message.Message()
msg['to']='billnowar@139.com'
msg['from']='billnowar@163.com'
msg['date']=time.ctime()
msg['subject']=email.Header.Header('weather','gb2312')
body=email.MIMEText.MIMEText(Tomorrow.encode('gb2312'),_subtype='plain',_charset='gb2312')

server=smtplib.SMTP('smtp server')
server.login('username','password')
server.sendmail(msg['from'],msg['to'],msg.as_string()[:-1]+body.as_string())

这上面这个是用python自带的库写的,学习了以下email和smtplib后很快就告成的版本

接下来就不容易了,我把email和smtplib、urllib改成了from google.appengine.api import mail和from google.appengine.api import urlfetch这两个……(因为不知到email和smtplib、urllib能不能用……)

然后又出现了编码问题……我不知道gae上到底该用utf-8还是别的什么,而且我也不清楚我手机是用什么编码(这个最麻烦)……

经过实验,发现根本不用改编码,全部都用utf8即可,百度天气是utf-8,所以省去了很多不必要的代码

忙活了两个多小时,终于还是让我搞成了!

通过写这个程序,初步了解了一下gae的机制:

1.GAE貌似可以使用所有的python自带库,既然re可以,那么其他的库理应也可以,这个没有实验,但是猜想应该是可以

2.GAE的cron,掌握了cron的基本写法,先写间隔 再写周期 再写具体时间

3.GAE编码用utf-8,这个实际有点废话……

4.GAE的google.appengine.api.mail.send_mail的sender参数应该添你的gmail邮箱,负责无法使用……

东方天宇 说:
2011年2月05日 20:08

谢谢。学习了。早听说GAE很帅,但不会python让我很无奈。在学校php。用php也可以实现这个功能。但是需要web激活,听说GAE有机器人?方便了很多呀


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter