Python學習筆記-實現探測Web服務質量

    pycurl是一個用C語言寫的libcurl Python實現,功能非常強大,支持的操作協議後FTP、HTTP、HTTPS、TELNET等,可以理解成Linux下curl命令功能的Python封裝,簡單易用

    本例通過調用pycurl提供的方法,實現探測Web服務質量的情況,比如響應HTTP狀態碼、請求延時、HTTP頭信息、下載速度等,利用這些信息可以定位服務響應慢的具體環節。

    pycurl.Curl()類實現創建一個libcurl包的Curl句柄對象,無參數。

    close()方法,對應的libcurl包中的curl_easy_cleanup方法,無參數,實現關閉、回收Curl對象。

    perform()方法,對應libcurl包中的curl_easy_perform方法,無參數,實現Curl對象請求的提交。

    setopt(option,value)方法,對應libcurl包中的curl_easy_setopt方法,參數option是通過libcurl的常量來指定的,參數value的值依賴option,可以是一個字符串、整型、長整型、文件對象、列表或函數等

安裝pycurl模塊

[root@kurol ~]# python3 -m easy_install -i http://pypi.douban.com/simple/ pycurl

報錯:

setuptools.sandbox.UnpickleableException: ConfigurationError("Could not run curl-config: [Errno 2] No such file or directory: 'curl-config'",)


先安裝libcurl-devel解決:

[root@kurol ~]# yum -y install libcurl-devel
[root@kurol ~]# python3 -m easy_install -i http://pypi.douban.com/simple/ pycurl
Finished processing dependencies for pycurl
#!/usr/bin/python3
# _*_ coding:utf-8 _*_
import sys,os
import time
import pycurl

url = "http://fm.mykurol.com"   #探測的目標URL
c = pycurl.Curl()   #創建一個Curl對象
c.setopt(pycurl.URL,url)    #定義請求的URL常量
c.setopt(pycurl.CONNECTTIMEOUT,5)   #定義請求連接的等待時間
c.setopt(pycurl.TIMEOUT,5)      #定義請求超時時間
c.setopt(pycurl.NOPROGRESS,1)       #屏蔽下載進度條
c.setopt(pycurl.FORBID_REUSE,1)     #完成交互後強制斷開連接,不重用
c.setopt(pycurl.MAXREDIRS,1)        #指定HTTP重定向的最大數爲1
c.setopt(pycurl.DNS_CACHE_TIMEOUT,30)       #設置保存DNS信息的時間爲30秒
#創建一個文件對象,以"web"方式打開,用來存儲返回的http頭部及頁面內容
indexfile = open(os.path.dirname(os.path.realpath(__file__))+"/content.txt","wb")
c.setopt(pycurl.WRITEHEADER, indexfile)     #將返回的HTTP HEADER定向到indexfile文件
c.setopt(pycurl.WRITEDATA, indexfile)       #將返回的HTML內容定向到indexfile文件對象
try:
    c.perform()
except Exception as e:
    print ("connection error:"+str(e))
    indexfile.close()
    c.close()
    sys.exit()

NAMELOOKUP_TIME = c.getinfo(c.NAMELOOKUP_TIME)  #獲取DNS解析時間
CONNECT_TIME = c.getinfo(c.CONNECT_TIME)    #獲取建立連接時間
PRETRANSFER_TIME = c.getinfo(c.PRETRANSFER_TIME)    #獲取從建立連接到準備傳輸所消耗的時間
STARTTRANSFER_TIME = c.getinfo(c.STARTTRANSFER_TIME)    #獲取從建立連接到傳輸開始消耗的時間
TOTAL_TIME = c.getinfo(c.TOTAL_TIME)    #獲取傳輸的總時間
HTTP_CODE = c.getinfo(c.HTTP_CODE)      #獲取HTTP狀態碼
SIZE_DOWNLOAD = c.getinfo(c.SIZE_DOWNLOAD)      #獲取下載數據包的大小
HEADER_SIZE = c.getinfo(c.HEADER_SIZE)      #獲取HTTP頭部大小
SPEED_DOWNLOAD = c.getinfo(c.SPEED_DOWNLOAD)    #獲取平均下載速度
#打印輸出相關數據
print ("HTTP狀態碼:%s" % (HTTP_CODE))
print ("DNS解析時間:%.2f ms" % (NAMELOOKUP_TIME*1000))
print ("建立連接時間:%.2f ms" % (CONNECT_TIME*1000))
print ("準備傳輸時間:%.2f ms" % (PRETRANSFER_TIME*1000))
print ("傳輸開始時間:%.2f ms" % (STARTTRANSFER_TIME*1000))
print ("傳輸結束總時間:%.2f ms" % (TOTAL_TIME*1000))
print ("下載數據包大小:%d bytes/s" % (SIZE_DOWNLOAD))
print ("HTTP頭部大小:%d bytes/s" % (HEADER_SIZE))
print ("平均下載速度:%d bytes/s" % (SPEED_DOWNLOAD))
#關閉文件及curl對象
indexfile.close()
c.close()


執行結果:

HTTP狀態碼:200
DNS解析時間:17.44 ms
建立連接時間:17.88 ms
準備傳輸時間:17.89 ms
傳輸開始時間:39.79 ms
傳輸結束總時間:39.88 ms
下載數據包大小:2526 bytes/s
HTTP頭部大小:389 bytes/s
平均下載速度:63333 bytes/s

查看獲取的HTTP文件頭部及頁面內容content.txt

HTTP/1.1 200 OK
Date: Fri, 09 Jun 2017 03:01:46 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Set-Cookie: PHPSESSID=qmhmq2hkbb3v5hs67rf38c5006; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 2526
Connection: close
Content-Type: text/html; charset=UTF-8
 
 
<!doctype html>
<link href="css.css" rel="stylesheet" type="text/css" />
<title>MyKurol電影推薦網</title>
<link rel="icon" href="p_w_picpath/logo.ico" type="img/x-ico" />
<body>
<link rel="icon" href="p_w_picpath/logo.ico" type="img/x-ico" />
<div class="in">
    <div class="header">
        <div class="mykurol">
            <a href="index.php" class="biaoyu"><strong>本網站由謝育政設計</strong></a>
        </div>
        <div class="key-sousuo">
            <input type="text" name="mo_key" placeholder="電影/導演/演員">
            <input type="submit" name="mo_sub" value="搜索">
        </div>
        <div class="Inlogin">
            <a href="MovEncy.php" class="movie-ency">電影大全</a>
            <a href="#" class="movie-guess">猜一猜</a>
            <a href="#" class="movie-album">電影專輯</a>
            <a href="login.php" class="login-sub">登錄</a><a href="reg.php" class="reg-sub">註冊</a>        </div>
    </div>
</div>
<div style="z-index:999; position:absolute; right: 20px; bottom:40%">
	<div>
    	<img src="p_w_picpath/1495501340.png" style="width:120px;"/>
    </div>
    <div style="padding:0; margin:0; background-color:#FFF; width:120px; height:30px">
    <a style="color:#666; font-size:12px;">友情鏈接:<a href="http://www.mygdmec.cn" style="text-decoration:none; color:#F9F; font-size:12px">凡夢購物網</a>
    </div>
</div>        <div class="body">
            <div class="flo">
                <div class="flo-biaoti">
                    <p href="#" class="movie-name" data-toggle="tooltip" title="《生化危機6》的詳細介紹"><strong>生化危機6</strong></p>
                    <p class="movie-jieshao">
                        在華盛頓特區愛麗絲被威斯克背叛後人類幾乎要失去最後的希望。作爲唯一的倖存者,也是人類對抗殭屍大軍的最後防線,愛麗絲必須回到噩夢開始的地方——浣熊市。在那裏保護傘公司正在集結所有的力量企圖對殘餘的倖存者發起最後的打擊。<br>
                        導演:保羅·安德森<br>
                        主演:米拉·喬沃維奇 ,伊恩·格雷,艾麗·拉特,魯比·羅絲,李準基,肖恩·羅伯茨,威廉·利維,伊恩·馬肯 <br>
                        動作 / 驚悚 / 科幻
                    </p>                </div>
 
            </div>
 
        </div>
        <div class="foot">
 
        </div>
    </div>
</body>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章