如何让Flask等待?

时间:2019-04-04 12:11:04

标签: python flask time

我正在运行一个处理请求的程序。我需要将反馈时间写入数据库。这段代码可以正常工作,但是它经常更新我的数据库。如何使index()方法等待60秒? time.sleep(60)在这里不起作用。

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)

1 个答案:

答案 0 :(得分:0)

正如评论中已经建议的那样,使用一些专用的任务队列可能是最好的解决方案。如果您不想带来任何依赖性,则可以改编以下简单示例:

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()

测试:

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

输出:

(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

如您所见,worker进行的实际工作之间存在1秒钟的延迟,因此立即处理了HTTP请求。