多線程-http請求

  • 線程基類
import threading
class base_thread(threading.Thread):
    def __init__(self, func):
        threading.Thread.__init__(self)
        self.func = func
        #print(type(self.func))
    def run(self):
        self.func
  • http請求
#-*- coding: utf-8 -*-
import requests
import json
class ConfigHttp:
    def __init__(self, host, port,headers):
        self.host = host
        self.port = port
        self.headers = headers
    # 封裝HTTP GET請求方法
    def get(self, url, params):
        # params = urllib.parse.urlencode(params)
        url = "http://"+self.host+":"+self.port+url
        try:
            r = requests.get(url, params=params, headers=self.headers)
            r.encoding = 'UTF-8'
            return r.text
        except Exception:
            print('no json data returned')
            return {}
    # 封裝HTTP POST請求方法,支持上傳圖片
    def post(self, url, data, files=None):
        data = eval(data)
        url = 'http://' + self.host + ':' + str(self.port)+url
        r =requests.post(url, files=files, data=data)
        print(data)
        json_response = r.text
        return json_response
  • 簡單調用,當然最好的方式是再次封裝一層
import ConfigHttp   
def sample_request():
    headers= {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0'}
    cf = ConfigHttp(host="www.xxx.com",port=80,headers=headers)
    #cf.get(url="/api/getuserinfo",{"id":2})
    cf.get(url="/api/getuserinfo?id=2")
  • 多線程調用
def multi_thread():
    count = 100
    threads = []
    for i in range(0, 100):
        threads.append(base_thread(sample_request()))
    for j in range(0, 100):
        threads[j].start()
    for k in range(0, 100):
        threads[k].join()
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • 線程 引言&動機 考慮一下這個場景,我們有10000條數據需要處理,處理每條數據需要花費1秒,但讀取數據只需要0....
    不浪漫的浪漫_ea03閱讀 375評論 0 0
  • 引言&動機 考慮一下這個場景,我們有10000條數據需要處理,處理每條數據需要花費1秒,但讀取數據只需要0.1秒,...
    chen_000閱讀 527評論 0 0
  • 基礎1.r''表示''內部的字符串默認不轉義2.'''...'''表示多行內容3. 布爾值:True、False(...
    neo已經被使用閱讀 1,724評論 0 5
  • 剛才看新聞才知道孫楊奪得了今年國際泳聯游泳世錦賽的冠軍,真是替他開心,一直都很喜歡他,看他參加綜藝節目時就覺得這個...
    V加加布魯根閱讀 523評論 0 1