arti_lina
arti_lina

Reputation: 115

How can I make Flask wait?

I'm running a program that works with requests. I need to write the feedback time to my database. This code works fine, but it updates my DB too often. How can I make index() method wait for 60s? time.sleep(60) doesn't work here.

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

dbconn = mysql.connector.connect(host="myhost", 
                             database='mydb', 
                      user='root', password='12345')

@app.route('/', methods = ['GET', 'POST'])
def index():
    if request.method == 'POST':
        cursor = dbconn.cursor()
        time_check = datetime.datetime.now()
        query = ("update mytable set response_time=%s where service_name = 'my_service'")
        param = time_check
        cursor.execute(query, (param,))
        print("sent query")
        dbconn.commit()
        cursor.close()
        #time.sleep(60)

    return render_template('index.html')

if __name__ == '__main__':
    app.run(host = "myhostaddress", port = 1010)

Upvotes: 5

Views: 10238

Answers (1)

Tomáš Linhart
Tomáš Linhart

Reputation: 10210

As already suggested in the comment, using some dedicated task queue would probably be the best solution. If you don't want to bring any dependency though, you might adapt this simple example:

from queue import Queue
import random
from threading import Thread
import time

from flask import Flask


app = Flask(__name__)


@app.route('/')
def index():
    n = random.randint(0, 100)
    q.put(n)
    return '%s\n' % n


def worker():
    while True:
        item = q.get()
        if item is None:
            break
        print('Processing %s' % item)  # do the work e.g. update database
        time.sleep(1)
        q.task_done()


if __name__ == '__main__':
    q = Queue()
    t = Thread(target=worker)
    t.start()
    app.run(host='0.0.0.0')
    q.join()
    q.put(None)
    t.join()

And the test:

pasmen@nyx:~$ for x in 1 2 3 4 5 6 7 8 9 10; do curl http://0.0.0.0:5000; done
1
90
79
25
45
50
77
25
36
99

Output:

(venv) pasmen@nyx:~/tmp/test$ python test.py 
 * Serving Flask app "test" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
Processing 1
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Apr/2019 14:57:57] "GET / HTTP/1.1" 200 -
Processing 90
Processing 79
Processing 25
Processing 45
Processing 50
Processing 77
Processing 25
Processing 36
Processing 99

As you can see, the HTTP requests are processed immediately while there's a 1 second delay between the actual work carried by worker.

Upvotes: 5

Related Questions