0

I'm creating a platform using flask+python where each loggedin user can add several social media accounts to be used for analysis. Each account added starts a new thread with the account name, which then is saved into a dic (key=account name and value=the thread). HOWEVER, when I do a hard refresh/reload on the homepage, the dic that references all the threads gets reset and returns None. I can make modifications, like get variable values from the threads or call the kill function to end the threads.I've been looking everywhere here on this site and I can't find the solution.

I've simplified my code:

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')     

Any help, ideas?

Haydar M.
  • 71
  • 1
  • 4
  • How about you use an actual database instead of an in-memory list/dict? – OneCricketeer Sep 17 '17 at 21:32
  • I could not edit so here's the 2 questions: Q1: What am I doing wrong? Q2: I'm running on the cheapest Ubuntu server from Digital-Ocean for 5$/month with 1 CPU. Is that good enough for this application or should I order a more expensive one with more CPU's? – Haydar M. Sep 17 '17 at 21:32
  • Note: using the Flask-Admin plugin does most the account management for you – OneCricketeer Sep 17 '17 at 21:33
  • Q2: That is off topic for StackOverflow. Do a proper benchmark for your application and monitor the CPU usage before paying more than necessary – OneCricketeer Sep 17 '17 at 21:34
  • Thanks for the tips. I'm using MySQL as a database. Could you elaborate a bit more about how to use my database instead of an in-memory dic? I'll look at Flask-Admin – Haydar M. Sep 17 '17 at 22:58
  • While you're reading Flask-Admin, it gives you the option to use sqlalchemy library for your accounts http://flask-admin.readthedocs.io/en/latest/adding_a_new_model_backend/?highlight=sql – OneCricketeer Sep 17 '17 at 23:00
  • I've already looked, however. Does not solve my issue with not being able to access the threads I've started after the website has been reloaded – Haydar M. Sep 21 '17 at 13:47
  • @cricket_007 I think you've misunderstood my issue. I don't need account management. I need a way to access running threads so I can control them – Haydar M. Sep 21 '17 at 13:49
  • It's not clear why you think you need threads at all. The HTML is rendered in one thread. If you need content dynamically added after that, you need Javascript, not Python – OneCricketeer Sep 21 '17 at 13:50
  • Sorry for the confusion. Threads is a must as I will be doing a bunch of calculations for each individual account added. It's about the backend and NOT frontend. Is it clear now @cricket_007 ? – Haydar M. Sep 23 '17 at 11:57
  • I understood that part from the question. However, as you've observed, your dictionary isn't preserved between web requests. Hence, I suggest you use a database to store account information. You're welcome to use threads, but they should be separate processes from the web server. You can add background processes via Celery, for example https://stackoverflow.com/questions/11256002/background-worker-with-flask – OneCricketeer Sep 23 '17 at 15:56

0 Answers0