0

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.

1
  • you have to run thread before app.run() (because app.run() is endless loop which runs till you stop server) Commented Dec 11, 2016 at 12:49

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.