python 簡單RPC示例

利用 SimpleXMLRPCServer 演示 簡單RPC例子

最后效果


demo.png

動圖演示

服務端

server.gif

客戶端

client.gif

思路:

服務器端 寫了一個小爬蟲渴丸,獲取豆瓣音樂的熱門榜,獲取數據冶忱。
客戶端 tcp 鏈接 服務器端袱箱,調用服務器爬蟲的方法,并得到返回數據式曲。將數據可視化圖表妨托。

需要安轉包

服務端 需要安裝 beautifulsoup4 來解析網頁,爬取數據
pip install beautifulsoup4

bs4.png

客戶端 需要安裝 flask web框架 和 pygal 生成圖表
pip install flask

flask.png

pip install pygal

pygal.png

代碼

服務器端代碼:

#-*- coding: utf-8 -*-
import urllib2
from bs4 import BeautifulSoup
import json
import string
from SimpleXMLRPCServer import SimpleXMLRPCServer
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')


def music():
    url = "https://music.douban.com/chart"

    html = urllib2.urlopen(url).read().decode("utf-8") 
    soup = BeautifulSoup(html,"html.parser") 

    items = soup.findAll('li',attrs={"class":"clearfix"},limit=8)
    print "starting..."
    
    print len(items)

    result = []
    nStr = ""
    for item in items:
        aTags = item.find('a')
        # get cover img
        img = aTags.find('img')
        img = img.attrs['src']
        img = nStr.join(img)
        # link
        link = aTags.attrs['href']
        link = nStr.join(link)
        # title
        title = item.find("h3").get_text()
        title = nStr.join(title)

        # team and num
        team = item.find("p").get_text()
        num = team.split("/")[1].strip()

        team = team.split("/")[0].strip()
        team = nStr.join(team)
        num = num.replace('次播放','')
        num = num.replace(' ','')
        num = nStr.join(num)
        num = int(num)
        # add to tuple
        result.append((img,link,title,team,num))

        # print img +" : "+ link + " : " + title + " : " + num +" : " + team
    # print result
    return result



address = raw_input("server address : ")

# A simple server with simple arithmetic functions
server = SimpleXMLRPCServer((address, 8000),  allow_none = True)
print "Listening on port 8000..."
server.register_multicall_functions()
server.register_function(music,'music')
server.serve_forever()

客戶端代碼
flask 結構如下

client
  app
    --static
    --templates
    views.py
    __init__.py
  run.py

static 文件夾內放 需要調用的js文件 pygal-tooltips.min.js 官網

templates文件夾內放置 html的模板文件

charts.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="{{url_for('static',filename='pygal-tooltips.min.js')}}"></script>
    <title>Python RPC</title>
</head>

<body>
    author: hejing
    <div id="chart">
        <embed type="image/svg+xml" src={{ chart|safe}}></embed>
    </div>
</body>

</html>

views.py

#-*- coding: utf-8 -*-

from app import app
import xmlrpclib
import pygal
from pygal.style import DefaultStyle
from flask import render_template
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')



@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"

@app.route('/musicHot')
def musicHot():
    address = raw_input("server address : ")
    proxy = xmlrpclib.ServerProxy("http://"+ address +":8000/", allow_none = True)
    multicall = xmlrpclib.MultiCall(proxy)
    multicall.music()
    result = multicall()
    result = tuple(result)
    total = 0;
    for i in range(len(result)):
        temp = result[i]
        for j in range(len(temp)):
            temp2 = temp[j]
            num = int(temp2[-1])
            total = total +  num
            
    # print total

    pie_chart = pygal.Pie(legend_at_bottom=True)
    title = pie_chart.title = '本周音樂人最熱單曲榜  '

    # print "----------\n"
    for i in range(len(result)):
        temp = result[i]
        for j in range(len(temp)):
            temp2 = temp[j]
            num = int(temp2[-1])
            percent = round((num*100.0) / (1.0*total),2)
            pie_chart.add(temp2[-3],percent)

            # for k in range(len(temp2)):
            #   # print temp2[k]
            #   if k == len(temp2):
            #       num = int(temp2[-1])
            #       percent = (num*100.0) / (1.0*total)
                
                

            # print "%d %.2f" % (num, percent ) 
            # print "----------\n"

    chart = pie_chart.render_data_uri()
    return render_template('charts.html', chart = chart)
    # return render_template('charts.html', chart = tuple(result))
 


@app.route('/show')
def show():
    pie_chart = pygal.Pie(egend_at_bottom=True)
    title = pie_chart.title = 'Browser usage in February 2012 (in %)'
    pie_chart.add('IE', 19.5)
    pie_chart.add('Firefox', 36.6)
    pie_chart.add('Chrome', 36.3)
    pie_chart.add('Safari', 4.5)
    pie_chart.add('Opera', 2.3)
    # chart = pie_chart.render()
    chart = pie_chart.render_data_uri()
    return render_template('charts.html', chart = chart)
    # return render_template('charts.html',chart = chart)
    # html = """
    # <html>
    # <head>
    # <title>%s</title>
    # </head>
    # <body>
    # %s
    # </body>
    # </html>
    # """ % (title, pie_chart.render())
    # return html

"init.py"

from flask import Flask

app = Flask(__name__)
from app import views

運行

服務端運行

$ python douban.py
server address : 

運行服務器端的 douban.py文件
會提示你輸入本機的ip
輸入完之后吝羞,服務器就一直運行

$ python douban.py
server address : 192.168.1.103
Listening on port 8000...

客戶端運行


$ python run.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 157-021-568

已經提示已經運行兰伤, 這個時候在瀏覽器上輸入
http://localhost:5000/ 就會顯示 Hello, World!

helloworld.png

我們地址再改成
http://localhost:5000/musicHot

$ python run.py 
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 157-021-568
127.0.0.1 - - [11/Oct/2016 13:55:58] "GET / HTTP/1.1" 200 -
server address : 

會提示讓你輸入服務端的地址

$ python run.py 
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 157-021-568
127.0.0.1 - - [11/Oct/2016 13:55:58] "GET / HTTP/1.1" 200 -
server address : 192.168.1.103
127.0.0.1 - - [11/Oct/2016 13:59:12] "GET /musicHot HTTP/1.1" 200 -

我們再看下瀏覽器

result.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市钧排,隨后出現的幾起案子敦腔,更是在濱河造成了極大的恐慌,老刑警劉巖恨溜,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件符衔,死亡現場離奇詭異找前,居然都是意外死亡,警方通過查閱死者的電腦和手機判族,發(fā)現死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門躺盛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人五嫂,你說我怎么就攤上這事颗品。” “怎么了沃缘?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵躯枢,是天一觀的道長。 經常有香客問我槐臀,道長锄蹂,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任水慨,我火速辦了婚禮得糜,結果婚禮上,老公的妹妹穿的比我還像新娘晰洒。我一直安慰自己朝抖,他們只是感情好,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布谍珊。 她就那樣靜靜地躺著治宣,像睡著了一般。 火紅的嫁衣襯著肌膚如雪砌滞。 梳的紋絲不亂的頭發(fā)上侮邀,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音贝润,去河邊找鬼绊茧。 笑死,一個胖子當著我的面吹牛打掘,可吹牛的內容都是我干的华畏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼胧卤,長吁一口氣:“原來是場噩夢啊……” “哼唯绍!你這毒婦竟也來了?” 一聲冷哼從身側響起枝誊,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎惜纸,沒想到半個月后叶撒,有當地人在樹林里發(fā)現了一具尸體绝骚,經...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年祠够,在試婚紗的時候發(fā)現自己被綠了压汪。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡古瓤,死狀恐怖止剖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情落君,我是刑警寧澤穿香,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站绎速,受9級特大地震影響皮获,放射性物質發(fā)生泄漏。R本人自食惡果不足惜纹冤,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一洒宝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧萌京,春花似錦雁歌、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至橡庞,卻和暖如春较坛,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背扒最。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工丑勤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人吧趣。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓法竞,卻偏偏與公主長得像,于是被迫代替她去往敵國和親强挫。 傳聞我的和親對象是個殘疾皇子岔霸,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內容

  • 22年12月更新:個人網站關停,如果仍舊對舊教程有興趣參考 Github 的markdown內容[https://...
    tangyefei閱讀 35,184評論 22 257
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理俯渤,服務發(fā)現呆细,斷路器,智...
    卡卡羅2017閱讀 134,657評論 18 139
  • 作者:詹聰聰 序言: 本人工作中需要用到flask-socketio八匠,在學習英文文檔時發(fā)現絮爷,flask-socke...
    Python中文社區(qū)閱讀 12,653評論 6 39
  • python學習筆記 聲明:學習筆記主要是根據廖雪峰官方網站python學習學習的趴酣,另外根據自己平時的積累進行修正...
    renyangfar閱讀 3,044評論 0 10
  • 學習 Flask,寫完一個 Flask 應用需要部署的時候坑夯,就想著折騰自己的服務器岖寞。根據搜索的教程照做,對于原理一...
    Cocoa_Coder閱讀 17,131評論 4 56