【发布时间】:2017-11-28 19:16:31
【问题描述】:
我尝试实施投票系统。它是这样工作的。如果用户对帖子进行投票,我会将其临时状态记录在会话变量中:upvoted、starred 等。
如果当前用户在我将结果保存到临时表之前还没有投票。用户可以在 5 分钟内更改投票。 5 分钟后,使用线程将结果永久写入数据库。
我想在结果写入数据库后清除临时会话变量。有没有办法做到这一点?
task.py
import threading
import time
from flask import Flask, copy_current_request_context, session
from threading import Lock
from vote import voteQuestion
app = Flask(__name__)
app.secret_key="appkey"
@app.before_first_request
def initializeTask():
@copy_current_request_context
def runTask():
while True:
voteQuestion()
time.sleep(10)
task = threading.Thread(target=runTask)
task.start()
@app.route('/vote')
def vote():
session['test'] = "This is a test"
return 'success'
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
app.run()
投票.py
from flask import session
def voteQuestion():
print('session variables', session.items())
result = session.get('test', 'not set')
print ('result ', result)
if 'test' in session:
session.pop('test', None)
print ('Running in the background')
【问题讨论】:
标签: python multithreading python-3.x flask