Python Threading Flask

时间:2017-09-17 21:27:48

标签: python multithreading flask

我正在使用flask + python创建一个平台,其中每个登录用户可以添加几个用于分析的社交媒体帐户。添加的每个帐户都会启动一个带有帐户名称的新主题,然后将其保存到一个dic(key =帐户名称和值=该主题)。但是,当我在主页上进行硬刷新/重新加载时,引用所有线程的dic将被重置并返回None。我可以进行修改,比如从线程中获取变量值或调用kill函数来结束线程。我已经在这个网站的任何地方查找,但我无法找到解决方案。

我简化了我的代码:

class threads_manager(threading.Thread):
    def __init__(self):
        super(threads_manager, self).__init__()

        self.cancelled = False
        self.accounts = {}

    def is_loggedin(self, username):
        if not self.accounts:
            return self.accounts[username].logged_in()

    def add_account(self, usname, uspass, PROXY):
        # AddAccount runs on a seperate thread that is managed by this thread
        acc = AddAccount(usname, uspass, '')
        acc.start()
        self.accounts.update({usname: acc})

    def kill_account(self, username):
        if self.accounts[username] != None:
            self.accounts[username].cancel()
            return True
        else:
            return False

    def run(self):
         # make sure that the thread kill it self after 1 min as I cant
         #get access to it later                     
         while not self.cancelled:
             if self.timeout > 0:
                time.sleep(2)
                self.timeout -= 1
            else:
                self.cancelled = True

# create new instance as global variable
manager = threads_manager()

@app.route('/addAccounts/')
def addAccounts():
    global manager
    # for displaying the accounts that are already stored in the server
        #shows the names of the running threads (ajax call)
        if request.args.get('command') == 'GETACCOUNTS':
            tnames = []
            for t in threading.enumerate():
                tnames.append(t.name)
            # prints the names as a flash/toast
            return jsonify({'success' : tname})
        if request.args.get('command') == 'ADDACCOUNT':
            #ajax call
            manager.add_account('username', 'password', 'proxy')
        else:
            #when reloading the website
            return render_template('addAccounts.html')     

任何帮助,想法?

0 个答案:

没有答案