在烧瓶中使用多线程来卷曲许多网址

时间:2015-04-14 08:52:06

标签: python multithreading flask

我有一个程序连接到大约20个网站并获取状态代码。我已经实现了多线程同时执行此操作。我想在烧瓶中创建的仪表板上显示相同的内容。我希望每次页面刷新时页面都会获取状态代码。

  @app.route('/')
  def dash():
    return  render_template('index.html', stats=stat)
    #return str(dataMap)

class myThread (threading.Thread):
    def __init__(self, threadID, url):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.url = url
    def run(self):
        print "Polling " + self.url
        # Get lock to synchronize threads
        threadLock.acquire()
        respose = urllib2.urlopen(link)
        stat.append(response.getcode())
        # Free lock to release next thread
        threadLock.release()


if __name__=="__main__":
    stat = []
    threadLock = threading.Lock()
    threads = []
    fob = open('links.txt','r')
    dataMap = yaml.safe_load(fob)
    i=1
    for link in dataMap:
        thread = myThread(i, link)
        thread.start()
        threads.append(thread)

    for t in threads:
        t.join()

    app.run(debug=True,host='0.0.0.0')

1 个答案:

答案 0 :(得分:0)

每次刷新根页面时,您都可以这样写,以便从URL获取信息。

stat = []
threadLock = threading.Lock()
threads = []
fob = open('links.txt','r')
dataMap = yaml.safe_load(fob)
i=1


@app.route('/')
def dash():
    global dataMap
    global threads
    for link in dataMap:
        thread = myThread(i, link)
        thread.start()
        threads.append(thread)

    for t in threads:
        t.join()
    return  render_template('index.html', stats=stat)

class myThread (threading.Thread):
    def __init__(self, threadID, url):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.url = url
    def run(self):
        print "Polling " + self.url
        # Get lock to synchronize threads
        global threadLock
        threadLock.acquire()
        respose = urllib2.urlopen(link)
        global stat
        stat.append(response.getcode())
        # Free lock to release next thread
        threadLock.release()


if __name__=="__main__":


    app.run(debug=True,host='0.0.0.0')