Answer the question
In order to leave comments, you need to log in
How to get variable from threading process in flask request?
Basically a question!
If the global variable changes in a separate thread, how can I get it through flask?
from flask import Flask
from threading import Thread
import time
import random
a='test'
def name():
while True:
time.sleep(1)
letters = 'test'
a=''.join(random.choice(letters) for i in range(len(letters)))
th = Thread(target=name)
th.start()
app = Flask(__name__)
@app.route("/")
def hello():
return a
if __name__ == "__main__":
app.run()
Answer the question
In order to leave comments, you need to log in
Because during the assignment in name() you create a local variable a that overrides the global one.
There are two solutions:
1. Simple: insert the string global a at the beginning of name() to work with the global variable
2. Correct: wrap the stream in a class, and work with its instance variable instead of the global one.
By the way, when starting the thread, add daemon=True, otherwise your thread will not allow the server to shut down (aka while True).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question