How do you add a background thread to flask in Python?

0 votes
I'm trying to write a game server to try out flask. The game exposes an API via REST to users.

It's easy for users to perform actions and query data, however I'd like to service the "game world" outside the app.run() loop to update game entities, etc.

 Given that Flask is so cleanly implemented, I'd like to see if there's a Flask way to do this. Need some help!
Nov 19, 2018 in Python by Anirudh
• 2,080 points
24,190 views

1 answer to this question.

0 votes

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app
answered Nov 19, 2018 by Nymeria
• 3,520 points
Hi,

Can you re-start the background task from specific routes throughout your app? I want a background task that starts based on the user who logs in into my app. For this, I believe I would need to access flask_login.current_user. How do I do that? Also, I want the background task to start once the user logs in, not before.

Your help would be very appreciated!

Thanks in advance

Hi, @Daniel Gutierrez,

Do you want a whole source code where access flask_login.current_user would be mention according to your query?

Hello, @Danial,

You can use this below given to login first and then start with background task:

def refresh_user():
    auth_methods = {am.name: am for am in current_app.auth_methods}
    user_auth_method = auth_methods[flask_login.current_user.authmethod]
    if user_auth_method.refresh(flask_login.current_user):
        current_app.logger.debug("Marking '{}' as fresh".format(
            flask_login.current_user))
        flask_login.confirm_login()
        # Call the original endpoint
        view = current_app.view_functions[request.endpoint]
        return view(**request.view_args)
    else:
        flash(login_manager.needs_refresh_message,
                category=login_manager.needs_refresh_message_category)
        original_url = url_for(request.endpoint, **request.view_args)
        return redirect(url_for('login.login', next=original_url,
                _anchor=user_auth_method.safe_name)) 

Related Questions In Python

0 votes
1 answer

How to add a new line in Python?

You can use '\n' for a next ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
345 views
+2 votes
1 answer

How do you make a block comment in python?

''' This is a multiline comment. I ...READ MORE

answered Aug 23, 2018 in Python by Priyaj
• 57,660 points
148 views
0 votes
2 answers

How do I connect to a MySQL Database in Python?

connect mysql database with python import MySQLdb db = ...READ MORE

answered Mar 28, 2019 in Python by rajesh
• 1,230 points
523 views
0 votes
1 answer

How do I use urllib to see if a website is 404 or 200 in Python?

For Python 3, try doing this: import urllib.request, ...READ MORE

answered Nov 29, 2018 in Python by Nymeria
• 3,520 points

edited Dec 11, 2018 by Nymeria 5,781 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,369 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
1,012 views
0 votes
1 answer

List comprehension on a nested list - How to do it in Python?

Not sure what your desired output is, ...READ MORE

answered Nov 21, 2018 in Python by Nymeria
• 3,520 points
521 views
0 votes
1 answer

Question on PyQt: How to connect a signal to a slot to start a background operation in Python

It shouldn't matter whether the connection is ...READ MORE

answered Nov 27, 2018 in Python by Nymeria
• 3,520 points
568 views