我如何让Flask等待?

问题描述 投票:0回答:1

我正在运行一个处理请求的程序。我需要将反馈时间写入我的数据库。此代码工作正常,但它经常更新我的数据库。如何使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)
python flask time
1个回答
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请求。

© www.soinside.com 2019 - 2024. All rights reserved.