利用 GAE同步更新饭否与TWITTER,建立你的HELLOTXT

第一次写与API有关的东西,算是一边练习Python及GAE,一边练习API接口的相关的操作。这是我做的一个利用GAE同步更新饭否与 TWITTER的DEMO,不保存帐户信息,每次需要手工填入用户名密码,再加入数据库存储等相应辅助模块即可做出与HelloTxt、Ping.fm类似的应用。

#!/usr/bin/env python
#coding:utf-8 
 
import wsgiref.handlers
import urllib
import base64
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
 
class MainPage(webapp.RequestHandler):
 
  def get(self):
    #self.response.headers['Content-Type'] = 'text/plain'
    self.response.headers.add_header("Expires", "Thu, 01 Dec 1994 16:00:00 GMT")
    header(self)
    self.response.out.write('''
Twitter username: password:
Fanfou username: password:
''') footer(self) class PostPage(webapp.RequestHandler): def post(self): header(self) msg = self.request.get('content') page_msg=msg msg = msg.encode('utf8') tu = self.request.get('tusername') tp = self.request.get('tpassword') fu = self.request.get('fu') fp = self.request.get('fp') #update(tu,tp,'twitter',msg) #update(fu,fp,'fanfou',msg) self.response.out.write('''
''') if update(tu,tp,'twitter',msg)==True: self.response.out.write('''

Twitter Post Susscessful

''') else: self.response.out.write('''

Twitter Post Faild

''') if update(fu,fp,'fanfou',msg)==True: self.response.out.write('''

Fanfou Post Susscessful

''') else: self.response.out.write('''

Fanfou Post Faild

''') self.response.out.write('''

Back

''') footer(self) #self.redirect('/') def header(self): self.response.out.write(''' Hello,World ''') def footer(self): self.response.out.write(''' ''') def update(username,password,twitter,msg): authStr = username + ":" + password #self.response.out.write(authStr.encode("base64")[0:-1]) if twitter=='twitter' : url='http://twitter.com/statuses/update.json' else: url='http://api.fanfou.com/statuses/update.json' #msg="Update by GAE.由GAE更新." form_fields = {"status":msg} form_data = urllib.urlencode(form_fields) #self.response.out.write(form_data) result = urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST, headers={"Content-type": "application/x-www-form-urlencoded", "Accept": "text/xml", "Authorization": "Basic "+authStr.encode("base64")[0:-1]}) if result.status_code == 200: return True else: return False def main(): application = webapp.WSGIApplication([('/', MainPage), ('/sign', PostPage)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()

-EOF-

发表评论

电子邮件地址不会被公开。 必填项已用*标注