python实战–web.py实战(开发新浪微博应用)


刚刚接触web.py,喜欢它的简洁与简单……于是打算实践一下,就有了下面的东西.感觉写的不是很好,有很多需要改进的地方….

源代码下载地址:点击打开链接

主要代码如下:

[python] view plaincopy

 

  1. #coding=utf-8

  2. “””

  3. 本应用主要功能

  4. 1.用户选择喜欢的标签加关注

  5. 2.获取用户粉丝中自己还没有关注的,->加关注,提高粉丝稳定性

  6. 3.获取用户关注列表中没有回粉的,并可以一键取消关注

  7. 2,3两个功能基本实现,有一缺点,数据量一大,很慢很慢

  8. 1功能不太好,主要是通过一个线程去搜索数据,把感兴趣的用户放入数据库,当用户选择加关注标签时,从数据库中取数据,

  9. 以前用sqlite3比较少,一用发现还是有好多值得研究的地方,主要是线程安全….,慢慢研究….

  10. “””

  11.  

  12. import os

  13. import sys

  14. import key

  15. import web

  16. import threading

  17. import sqlite3

  18. import time

  19. from weibopy.auth import OAuthHandler

  20. from weibopy.api import API

  21. from jinja2 import Environment,FileSystemLoader

  22.  

  23. “””

  24. url配置

  25. “””

  26. urls = (

  27.      ‘/’‘Login’,

  28.      ‘/index’,‘Index’,

  29.      ‘/callback’,‘CallBack’,

  30.      ‘/logout’,‘LogOut’,

  31.      ‘/(.*)/’‘Redirect’,

  32.      ‘/tag’‘Tag’,

  33.      ‘/noattention’,‘Noattention’,

  34.      ‘/fensiattention’,‘Fensiattention’,

  35.      ‘/minusattention’,‘Minusattention’,

  36.      ‘/delattention’,‘Delattention’

  37.  )

  38.  

  39. app=web.application(urls,globals())

  40.  

  41. if web.config.get(‘_session’is None:

  42.      session = web.session.Session(app,web.session.DiskStore(“sina”))

  43.      web.config._session = session

  44. else:

  45.      session = web.config._session

  46.  

  47. “””

  48.    用jinja2模板渲染文件

  49. “””

  50. def render_template(template_name,**context):

  51.      extensions=context.pop(‘extensions’,[])

  52.      globals=context.pop(“globals”,{})

  53.      jinja_env=Environment(

  54.          loader=FileSystemLoader(os.path.join(os.path.dirname(__file__),‘templates’)),

  55.          extensions=extensions)

  56.      jinja_env.globals.update(globals)

  57.      return jinja_env.get_template(template_name).render(context)

  58.  

  59.  

  60. “””

  61. 定义404请求页面

  62. “””

  63. def notfound():

  64.      info=“亲,您所请求的页面不存在,系统在3秒后自动返回…”

  65.      return web.notfound(render_template(‘error.html’,info=info.decode(‘utf-8′)))

  66.  

  67. db=web.database(dbn=‘sqlite’,db=‘tag.s3db’)

  68.  

  69. “””

  70. 要求tag

  71. “””

  72. tagdict={‘水瓶座’:1,‘双鱼座’:2,‘白羊座’:3,‘金牛座’:4,‘双子座’:5,‘巨蟹座’:6,‘狮子座’:7,‘处女座’:8,‘天秤座’:9,‘天蝎座’:10,‘射手座’:11,

  73.          ‘摩羯座’:12,‘吃’:13,‘听歌’:14,‘淘宝’:15,‘网购’:16,‘数码’:17,‘摄影’:18,‘睡觉’:19,‘旅游’:20,‘体育’:21,‘动漫’:22,‘游戏’:23,

  74.          ‘股票’:24,‘交友’:25,‘宅女’:26,‘宅男’:27,‘时尚’:28,‘浪漫’:29,‘美女’:30,‘创业’:31,‘IT’:32,‘媒体’:33,‘营销’:34}

  75. systag=[‘水瓶座’,‘双鱼座’,‘白羊座’,‘金牛座’,‘双子座’,‘巨蟹座’,‘狮子座’,‘处女座’,‘天秤座’,‘天蝎座’,‘射手座’,‘摩羯座’,‘吃’,‘听歌’,‘淘宝’,

  76.         ‘网购’,‘数码’,‘摄影’,‘睡觉’,‘旅游’,‘体育’,‘动漫’,‘游戏’,‘股票’,‘交友’,‘宅女’,‘宅男’,‘时尚’,‘浪漫’,‘美女’,‘创业’,‘IT’,‘媒体’,‘营销’]

  77.  

  78. conn=sqlite3.connect(‘tag.s3db’,check_same_thread=False#允许其它线程使用这个连接

  79. conn.text_factory = str

  80. cursor=conn.cursor()

  81.  

  82. class Setag(threading.Thread):

  83.     “””

  84. 这个线程主要是用来搜索用户tag,如果满足tag要求就写入数据库中,

  85.     “””

  86.     def authorization(self):

  87.         “””

  88.         开发者认证

  89.         “””

  90.         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)

  91.         auth.setToken(key.TOKEN,key.TOKEN_SECRET)

  92.         self.api = API(auth)

  93.         self.cursor=cursor

  94.  

  95.     def adduser(self,uid):

  96.         “””

  97.         遍历uid用户的tag,满足条件加入数据库

  98.         “””

  99.         try:

  100.             fan=self.api.followers_ids(uid)

  101.             fanuid=fan.ids

  102.             for id in fanuid:

  103.                 tags=self.api.tags(id)

  104.                 tt=[]

  105.                 for t in tags:

  106.                     tagid=t.__getattribute__(‘id’)

  107.                     value=t.__getattribute__(tagid)

  108.                     tt.append(value.encode(‘utf-8′))

  109.                 “””

  110.                 获取用户tag与要求标签的交集

  111.                 “””

  112.                 common=set(tt).intersection(set(systag))

  113.                 if len(common)==0:

  114.                     continue

  115.                 else:

  116.                     for t in common:

  117.                         “””

  118.                         获取tag对应的tagid

  119.                         “””

  120.                         tagindex=tagdict[t]

  121.                         try:

  122.                             self.cursor.execute(“insert into taginfo(uid,tagid) values(%d,%d)” %(int(id),int(tagindex)))

  123.                             conn.commit()

  124.                         except:

  125.                             continue

  126.         except:

  127.             time.sleep(120)

  128.             pass

  129.         finally:

  130.             time.sleep(60)

  131.             “””

  132.             将uid用户的第一个粉丝uid传给adduser

  133.             “””

  134.             return self.adduser(fanuid[0])

  135.  

  136.     def run(self):

  137.         self.authorization()

  138.         me=self.api.verify_credentials()

  139.         “””

  140.         将我自己的uid给adduser

  141.         “””

  142.         self.adduser(me.id)

  143.  

  144. “””

  145. 定义404请求页面

  146. “””

  147. app.notfound= notfound

  148.  #首页

  149.  #首先从session中获取access_token,没有就转向新浪微博页面认证

  150.  #认证成功后将access_token保存在session中

  151. “””

  152. 首页是登陆页面,通过新浪微博授权

  153. “””

  154. class Login:

  155.     def GET(self):

  156.         return render_template(‘login.html’)

  157.  

  158. “””

  159. 新浪微博授权原理:

  160. 首先首页判断有无用户session信息,如果有则跳转到相应地址,

  161. 没有则引导用户跳转到授权uri,授权后自动跳转到永远自定义的回调地址,

  162. 回调地址保存用户session信息,跳转到首页,这时已有用户session信息,干坏事吧….

  163. “””

  164. class Index:

  165.      def GET(self):

  166.          access_token=session.get(‘access_token’,None)

  167.          if not access_token:

  168.              “””

  169.              key.py中放置了开发者的信息

  170.              “””

  171.              auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET,web.ctx.get(‘homedomain’)+‘/callback’)

  172.              #获取授权url

  173.              auth_url = auth.get_authorization_url()

  174.              session.request_token=auth.request_token

  175.              web.seeother(auth_url)

  176.          else:

  177.              auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)

  178.              auth.access_token=access_token

  179.              api=API(auth)

  180.              user=api.verify_credentials()

  181.              return render_template(‘index.html’,user=user)

  182.  

  183.  

  184. “””

  185.  页面回调,新浪微博验证成功后会返回本页面

  186. “””

  187. class CallBack:

  188.      def GET(self):

  189.          try:

  190.              ins=web.input()

  191.              oauth_verifier=ins.get(‘oauth_verifier’,None)

  192.              request_token=session.get(‘request_token’,None)

  193.              auth=OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)

  194.              auth.request_token=request_token

  195.              access_token=auth.get_access_token(oauth_verifier)

  196.              session.access_token=access_token

  197.              web.seeother(“/index”)

  198.          except Exception:

  199.              info=“亲,系统繁忙,请稍后再试……,系统在3秒后自动返回…”

  200.              return render_template(‘error.html’,info=info.decode(‘utf-8′))

  201.  

  202. “””

  203. 重定向用户输入uri后的/

  204. “””

  205. class Redirect:

  206.     def GET(self,path):

  207.         web.seeother(‘/’+path)

  208.  

  209. class Tag:

  210.     “””

  211.     获取用户选择加关注的tag

  212.     “””

  213.     def GET(self):

  214.         data=web.input()

  215.         try:

  216.             select=data.star

  217.         except:

  218.             try:

  219.                 select=data.hobby

  220.             except:

  221.                 try:

  222.                     select=data.personality

  223.                 except:

  224.                     select=data.job

  225.         try:

  226.             auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)

  227.             auth.access_token=session[‘access_token’]

  228.             api=API(auth)

  229.             seuid=[]

  230.             nu=0

  231.             “””

  232.             这里写的很不好…..

  233.             “””

  234.             while True:

  235.                 re=cursor.execute(‘select uid from taginfo where tagid=%d limit 20′ %select).fetchall()

  236.                 for r in re:

  237.                     seuid.append(r[0])

  238.                 for s in seuid:

  239.                     try:

  240.                         api.create_friendship(user_id=s)

  241.                         nu+=1

  242.                     except:

  243.                         continue

  244.                 if nu>=50:

  245.                     break

  246.  

  247.             info=“恭喜您已成功关注%d位用户…..” %nu

  248.             return render_template(‘success.html’,info=info.decode(‘utf-8′))

  249.         except:

  250.             info=“亲,系统繁忙,请稍后再试……,系统在3秒后自动返回…”

  251.             return render_template(‘error.html’,info=info.decode(‘utf-8′))

  252.  

  253. class Noattention:

  254.     “””

  255.     获取我的粉丝中我没有加关注的,把数据传给noattention.html页面显示…

  256.     “””

  257.     def GET(self):

  258.         try:

  259.             auth=OAuthHandler(key.CONSUME_KEY,key.CONSUME_SECRET)

  260.             auth.access_token=session[‘access_token’]

  261.             api=API(auth)

  262.             user=api.verify_credentials()

  263.             fan=[]

  264.             next_cursor=-1

  265.             while next_cursor!=0:

  266.                 timeline=api.followers(user.id,,,,next_cursor)

  267.                 if isinstance(timeline,tuple):

  268.                     next_cursor=timeline[1]

  269.                     for line in timeline[0]:

  270.                         fid=line.__getattribute__(“id”)

  271.                         fname=line.__getattribute__(“screen_name”)

  272.                         fan.append((fid,fname))

  273.  

  274.                 else:

  275.                     next_cursor=0

  276.                     for line in timeline:

  277.                         fid=line.__getattribute__(“id”)

  278.                         fname=line.__getattribute__(“screen_name”)

  279.                         fan.append((fid,fname))

  280.  

  281.             friend=[]

  282.             next_cursor=-1

  283.             while next_cursor!=0:

  284.                 timeline=api.friends(user.id,,,,next_cursor)

  285.                 if isinstance(timeline,tuple):

  286.                     next_cursor=timeline[1]

  287.                     for line in timeline[0]:

  288.                         frid=line.__getattribute__(“id”)

  289.                         frname=line.__getattribute__(“screen_name”)

  290.                         friend.append((frid,frname))

  291.                 else:

  292.                     next_cursor=0

  293.                     for line in timeline:

  294.                         frid=line.__getattribute__(“id”)

  295.                         frname=line.__getattribute__(“screen_name”)

  296.                         friend.append((frid,frname))

  297.             #获取我的粉丝中还不是我的关注对象

  298.             fanNotAttention=list(set(fan).difference(set(friend)))

  299.             nu=len(fanNotAttention)

  300.             if nu==0:

  301.                 return render_template(‘noattentionok.html’,nu=nu)

  302.             else:

  303.                 return render_template(‘noattention.html’,nu=nu,fanNotAttention=fanNotAttention)

  304.  

  305.         except:

  306.             info=“亲,系统繁忙,请稍后再试……,系统在3秒后自动返回…”

  307.             return render_template(‘error.html’,info=info.decode(‘utf-8′))

  308.  

  309. class Fensiattention:

  310.     “””

  311.     对未加关注的粉丝加关注

  312.     “””

  313.     def GET(self):

  314.         #获取noattentionok.html传过来的数据

  315.         data=web.input()

  316.         on=[]

  317.         try:

  318.             auth=OAuthHandler(key.CONSUME_KEY,key.CONSUME_SECRET)

  319.             auth.access_token=session[‘access_token’]

  320.             api=API(auth)

  321.             “””

  322.             获取noattention.html页面传过来的uid,通过checkbox,由于有一个全选按钮,如果点击,则去掉

  323.             “””

  324.             for x in data:

  325.                 on.append(x)

  326.             try:

  327.                 on.remove(‘checkbox2′)

  328.             except:

  329.                 pass

  330.             nu=len(on)

  331.             if nu==0:

  332.                 pass

  333.             if nu>60:

  334.                 on=on[:60]

  335.                 nu=60

  336.             “””

  337.             一次最多加60次关注

  338.             “””

  339.             map(api.create_friendship,on)

  340.             info=“恭喜您已成功关注%d位用户…..” %nu

  341.             return render_template(‘success.html’,info=info.decode(‘utf-8′))

  342.         except:

  343.              info=“亲,系统繁忙,请稍后再试……,系统在3秒后自动返回…”

  344.              return render_template(‘error.html’,info=info.decode(‘utf-8′))

  345.  

  346.  

  347. class Minusattention:

  348.     “””

  349.     获取我的关注中不是我粉丝的,即不回粉的家伙,把数据传给attentionnotfan.html显示…

  350.     “””

  351.     def GET(self):

  352.         try:

  353.             auth=OAuthHandler(key.CONSUME_KEY,key.CONSUME_SECRET)

  354.             auth.access_token=session[‘access_token’]

  355.             api=API(auth)

  356.             user=api.verify_credentials()

  357.             fan=[]

  358.             next_cursor=-1

  359.             while next_cursor!=0:

  360.                 timeline=api.followers(user.id,,,,next_cursor)

  361.                 if isinstance(timeline,tuple):

  362.                     next_cursor=timeline[1]

  363.                     for line in timeline[0]:

  364.                         fid=line.__getattribute__(“id”)

  365.                         fname=line.__getattribute__(“screen_name”)

  366.                         fan.append((fid,fname))

  367.  

  368.                 else:

  369.                     next_cursor=0

  370.                     for line in timeline:

  371.                         fid=line.__getattribute__(“id”)

  372.                         fname=line.__getattribute__(“screen_name”)

  373.                         fan.append((fid,fname))

  374.  

  375.             friend=[]

  376.             next_cursor=-1

  377.             while next_cursor!=0:

  378.                 timeline=api.friends(user.id,,,,next_cursor)

  379.                 if isinstance(timeline,tuple):

  380.                     next_cursor=timeline[1]

  381.                     for line in timeline[0]:

  382.                         frid=line.__getattribute__(“id”)

  383.                         frname=line.__getattribute__(“screen_name”)

  384.                         friend.append((frid,frname))

  385.                 else:

  386.                     next_cursor=0

  387.                     for line in timeline:

  388.                         frid=line.__getattribute__(“id”)

  389.                         frname=line.__getattribute__(“screen_name”)

  390.                         friend.append((frid,frname))

  391.             attentionNotFan=list(set(friend).difference(set(fan)))

  392.             nu=len(attentionNotFan)

  393.             if nu==0:

  394.                 return render_template(‘attentionnotfanok.html’,nu=nu)

  395.             else:

  396.                 return render_template(‘attentionnotfan.html’,nu=nu,attentionNotFan=attentionNotFan)

  397.  

  398.         except:

  399.              info=“亲,系统繁忙,请稍后再试……,系统在3秒后自动返回…”

  400.              return render_template(‘error.html’,info=info.decode(‘utf-8′))

  401.  

  402.  

  403. class Delattention:

  404.     “””

  405.     获取attentionnotfan.html页面选择的用户,并一键取消关注

  406.     “””

  407.     def GET(self):

  408.         #获取attentionnotfan.html传过来的数据

  409.         data=web.input()

  410.         on=[]

  411.         try:

  412.             auth=OAuthHandler(key.CONSUME_KEY,key.CONSUME_SECRET)

  413.             auth.access_token=session[‘access_token’]

  414.             api=API(auth)

  415.             for x in data:

  416.                 on.append(x)

  417.             try:

  418.                 #同理,由于有全选按钮…..

  419.                 on.remove(‘checkbox2′)

  420.             except:

  421.                 pass

  422.             nu=len(on)

  423.             if nu==0:

  424.                 pass

  425.             #取消关注

  426.             map(api.destroy_friendship,on)

  427.             info=“恭喜您已成功取消关注%d位用户…..” %nu

  428.             return render_template(‘success.html’,info=info.decode(‘utf-8′))

  429.         except:

  430.              info=“亲,系统繁忙,请稍后再试……,系统在3秒后自动返回…”

  431.              return render_template(‘error.html’,info=info.decode(‘utf-8′))

  432.  

  433. if __name__==‘__main__’:

  434.      “””

  435.      启动app,启动s线程去搜索数据

  436.      “””

  437.      s=Setag()

  438.      s.start()

  439.      app.run()

 

效果如下:

点击用微博账号登陆:

首页:

由于太长.所以图没截好,大家懂的…

当点击互粉按钮时…..

功能还有很多需要完善的地方……

上一篇 下一篇

评论



分享

最新加入

最新评论

隋中缘: @嘉嘉tiffany 性感乳神。 查看原文 06月13日 16:16