admin asd
admin asd

Reputation: 35

how to fix threading in python

I wrote the following python code

import thread
from flask import Flask

app = Flask(__name__)
COOKIE =""
@app.route('/')
def index():
    return COOKIE

def request_cookie():
     global COOKIE
     while 1:
         %SOME CODE WHICH GET COOKIE FROM WEB SITE%
         sleep 5

if __name__ == '__main__':
    app.run(debug=True)
    t1 = thread.start_new_thread(get_cookie(), ())
    t1.start()

When I run this code. REST server starts but the thread doesn't start.

How can I fix it so that REST server starts and parallely runs the new thread to fetch cookie from a remote site.

Upvotes: 0

Views: 249

Answers (2)

furas
furas

Reputation: 143187

You have to run thread before app.run() because app.run() runs endless loop which works till you stop server.

Working example:

from flask import Flask
import threading 
import time

app = Flask(__name__)

COOKIE = 0

@app.route('/')
def index():
    return str(COOKIE)

def request_cookie():
     global COOKIE

     while True:
         COOKIE += 1
         time.sleep(1)

if __name__ == '__main__':
    t1 = threading.Thread(target=request_cookie)
    t1.start()
    app.run(debug=True)

Upvotes: 0

Vikash Singh
Vikash Singh

Reputation: 14021

You are doing app.run(debug=True) which starts the web server and waits for it to complete. Since it doesn't complete till you terminate the server, the next line is not executed.

So for your thread to start, first start the thread and then start the server.

just change :

if __name__ == '__main__':
    t1 = thread.start_new_thread(get_cookie(), ())
    t1.start()
    app.run(debug=True)

Upvotes: 1

Related Questions