Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

web.py 實戰:動手做一個新浪微博應用

剛接觸 web.py,喜歡它的簡潔與簡單,於是打算動手實作,就有了下面這些東西。寫得還不成熟,但把過程記錄下來,或許對同樣剛入門的人有點參考價值。

這個應用主要完成三件事:

1. 讓使用者選擇感興趣的標籤並加關注;

2. 找出粉絲中自己尚未關注的人,一鍵加關注,藉此提高粉絲穩定性;

3. 找出自己關注清單中沒有回粉的人,並可一鍵取消關注。

其中第 2、3 項大致實現,缺點是資料量一大就非常慢。第 1 項的做法是開一條執行緒去搜尋資料,把符合條件的使用者寫入資料庫,使用者選擇標籤時再從庫中取用。另外,以前較少用 sqlite3,一用才發現值得研究的地方不少,主要是執行緒安全,需要慢慢摸索。

主要程式碼

#coding=utf-8
"""
本應用主要功能
1. 使用者選擇喜歡的標籤加關注
2. 獲取使用者粉絲中自己還沒有關注的 -> 加關注,提高粉絲穩定性
3. 獲取使用者關注列表中沒有回粉的,並可以一鍵取消關注
"""

import os
import sys
import key
import web
import threading
import sqlite3
import time
from weibopy.auth import OAuthHandler
from weibopy.api import API
from jinja2 import Environment, FileSystemLoader

urls = (
    '/',            'Login',
    '/index',       'Index',
    '/callback',    'CallBack',
    '/logout',      'LogOut',
    '/(.*)/',       'Redirect',
    '/tag',         'Tag',
    '/noattention', 'Noattention',
    '/fensiattention', 'Fensiattention',
    '/minusattention', 'Minusattention',
    '/delattention',   'Delattention'
)

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

if web.config.get('_session') is None:
    session = web.session.Session(app, web.session.DiskStore("sina"))
    web.config._session = session
else:
    session = web.config._session

def render_template(template_name, **context):
    extensions = context.pop('extensions', [])
    globals = context.pop("globals", {})
    jinja_env = Environment(
        loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')),
        extensions=extensions)
    jinja_env.globals.update(globals)
    return jinja_env.get_template(template_name).render(context)

def notfound():
    info = "親,您所請求的頁面不存在,系統在 3 秒後自動返回..."
    return web.notfound(render_template('error.html', info=info.decode('utf-8')))

db = web.database(dbn='sqlite', db='tag.s3db')

tagdict = {'水瓶座':1, '雙魚座':2, '白羊座':3, '金牛座':4, '雙子座':5,
           '巨蟹座':6, '獅子座':7, '處女座':8, '天秤座':9, '天蠍座':10,
           '射手座':11, '摩羯座':12, '吃':13, '聽歌':14, '淘寶':15,
           '網購':16, '數碼':17, '攝影':18, '睡覺':19, '旅遊':20,
           '體育':21, '動漫':22, '遊戲':23, '股票':24, '交友':25,
           '宅女':26, '宅男':27, '時尚':28, '浪漫':29, '美女':30,
           '創業':31, 'IT':32, '媒體':33, '營銷':34}
systag = list(tagdict.keys())

conn = sqlite3.connect('tag.s3db', check_same_thread=False)  # 允許其它執行緒使用這個連接
conn.text_factory = str
cursor = conn.cursor()

class Setag(threading.Thread):
    """這個執行緒主要用來搜尋使用者 tag,符合條件就寫入資料庫"""

    def authorization(self):
        auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
        auth.setToken(key.TOKEN, key.TOKEN_SECRET)
        self.api = API(auth)
        self.cursor = cursor

    def adduser(self, uid):
        """遍歷 uid 使用者的 tag,符合條件加入資料庫"""
        try:
            fan = self.api.followers_ids(uid)
            fanuid = fan.ids
            for id in fanuid:
                tags = self.api.tags(id)
                tt = []
                for t in tags:
                    tagid = t.__getattribute__('id')
                    value = t.__getattribute__(tagid)
                    tt.append(value.encode('utf-8'))
                # 獲取使用者 tag 與要求標籤的交集
                common = set(tt).intersection(set(systag))
                if len(common) == 0:
                    continue
                else:
                    for t in common:
                        tagindex = tagdict[t]
                        try:
                            self.cursor.execute(
                                "insert into taginfo(uid,tagid) values(%d,%d)"
                                % (int(id), int(tagindex)))
                            conn.commit()
                        except:
                            continue
        except:
            time.sleep(120)
            pass
        finally:
            time.sleep(60)
            # 將 uid 使用者的第一個粉絲 uid 傳給 adduser
            return self.adduser(fanuid[0])

    def run(self):
        self.authorization()
        me = self.api.verify_credentials()
        # 將我自己的 uid 給 adduser
        self.adduser(me.id)

app.notfound = notfound

class Login:
    """首頁是登陸頁面,透過新浪微博授權"""
    def GET(self):
        return render_template('login.html')

class Index:
    """首頁判斷有無使用者 session 資訊,有則跳轉,沒有則引導授權"""
    def GET(self):
        access_token = session.get('access_token', None)
        if not access_token:
            # key.py 中放置了開發者的資訊
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET,
                                web.ctx.get('homedomain') + '/callback')
            auth_url = auth.get_authorization_url()   # 獲取授權 url
            session.request_token = auth.request_token
            web.seeother(auth_url)
        else:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = access_token
            api = API(auth)
            user = api.verify_credentials()
            return render_template('index.html', user=user)

class CallBack:
    """頁面回調,新浪微博驗證成功後會返回本頁面"""
    def GET(self):
        try:
            ins = web.input()
            oauth_verifier = ins.get('oauth_verifier', None)
            request_token = session.get('request_token', None)
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.request_token = request_token
            access_token = auth.get_access_token(oauth_verifier)
            session.access_token = access_token
            web.seeother("/index")
        except Exception:
            info = "親,系統繁忙,請稍後再試......,系統在 3 秒後自動返回..."
            return render_template('error.html', info=info.decode('utf-8'))

class Redirect:
    """重定向使用者輸入 uri 後的 /"""
    def GET(self, path):
        web.seeother('/' + path)

class Tag:
    """獲取使用者選擇加關注的 tag"""
    def GET(self):
        data = web.input()
        try:
            select = data.star
        except:
            try:
                select = data.hobby
            except:
                try:
                    select = data.personality
                except:
                    select = data.job
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            seuid = []
            nu = 0
            while True:
                re = cursor.execute(
                    'select uid from taginfo where tagid=%d limit 20' % select).fetchall()
                for r in re:
                    seuid.append(r[0])
                for s in seuid:
                    try:
                        api.create_friendship(user_id=s)
                        nu += 1
                    except:
                        continue
                if nu >= 50:
                    break

            info = "恭喜您已成功關注 %d 位使用者....." % nu
            return render_template('success.html', info=info.decode('utf-8'))
        except:
            info = "親,系統繁忙,請稍後再試......,系統在 3 秒後自動返回..."
            return render_template('error.html', info=info.decode('utf-8'))

class Noattention:
    """獲取我的粉絲中我沒有加關注的,傳給 noattention.html 顯示"""
    def GET(self):
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            user = api.verify_credentials()
            fan = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.followers(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))
                else:
                    next_cursor = 0
                    for line in timeline:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))

            friend = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.friends(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))
                else:
                    next_cursor = 0
                    for line in timeline:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))

            # 獲取我的粉絲中還不是我的關注對象
            fanNotAttention = list(set(fan).difference(set(friend)))
            nu = len(fanNotAttention)
            if nu == 0:
                return render_template('noattentionok.html', nu=nu)
            else:
                return render_template('noattention.html', nu=nu,
                                       fanNotAttention=fanNotAttention)
        except:
            info = "親,系統繁忙,請稍後再試......,系統在 3 秒後自動返回..."
            return render_template('error.html', info=info.decode('utf-8'))

class Fensiattention:
    """對未加關注的粉絲加關注"""
    def GET(self):
        data = web.input()      # 獲取 noattention.html 傳過來的資料
        on = []
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            # 由於有全選按鈕,若點擊則需去掉 checkbox2
            for x in data:
                on.append(x)
            try:
                on.remove('checkbox2')
            except:
                pass
            nu = len(on)
            if nu > 60:      # 一次最多加 60 次關注
                on = on[:60]
                nu = 60
            map(api.create_friendship, on)
            info = "恭喜您已成功關注 %d 位使用者....." % nu
            return render_template('success.html', info=info.decode('utf-8'))
        except:
            info = "親,系統繁忙,請稍後再試......,系統在 3 秒後自動返回..."
            return render_template('error.html', info=info.decode('utf-8'))

class Minusattention:
    """獲取我的關注中不是我粉絲的,即不回粉傢伙"""
    def GET(self):
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            user = api.verify_credentials()
            fan = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.followers(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))
                else:
                    next_cursor = 0
                    for line in timeline:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))

            friend = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.friends(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))
                else:
                    next_cursor = 0
                    for line in timeline:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))

            attentionNotFan = list(set(friend).difference(set(fan)))
            nu = len(attentionNotFan)
            if nu == 0:
                return render_template('attentionnotfanok.html', nu=nu)
            else:
                return render_template('attentionnotfan.html', nu=nu,
                                       attentionNotFan=attentionNotFan)
        except:
            info = "親,系統繁忙,請稍後再試......,系統在 3 秒後自動返回..."
            return render_template('error.html', info=info.decode('utf-8'))

class Delattention:
    """獲取 attentionnotfan.html 頁面選擇的使用者,並一鍵取消關注"""
    def GET(self):
        data = web.input()      # 獲取 attentionnotfan.html 傳過來的資料
        on = []
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            for x in data:
                on.append(x)
            try:
                on.remove('checkbox2')   # 同理,由於有全選按鈕
            except:
                pass
            nu = len(on)
            map(api.destroy_friendship, on)   # 取消關注
            info = "恭喜您已成功取消關注 %d 位使用者....." % nu
            return render_template('success.html', info=info.decode('utf-8'))
        except:
            info = "親,系統繁忙,請稍後再試......,系統在 3 秒後自動返回..."
            return render_template('error.html', info=info.decode('utf-8'))

if __name__ == '__main__':
    # 啟動 app,並啟動執行緒去搜尋資料
    s = Setag()
    s.start()
    app.run()

實作心得

整個流程分成兩條線:主執行緒負責 web.py 的路由與 OAuth 授權(Login 導向授權頁、CallBack 接收 verifier 並換取 access_token 存進 session),背景執行緒 Setag 則不間斷地爬取粉絲的 tag 寫入 sqlite。使用者操作時,各頁面再用集合的差集運算(set(fan).difference(set(friend)) 及其反向)算出「我沒關注的粉絲」與「沒回粉的關注」,最後以 map 批次呼叫 API 完成關注或取消關注。

仍有許多需要完善之處:資料量大時查詢與 API 呼叫都偏慢、sqlite3 在多執行緒下的寫入需要更嚴謹的鎖處理、以及 map 批次操作缺乏速率控制,都是後續可以改進的方向。

Copyright © Linux教程網 All Rights Reserved