Flask从线程中删除会话变量

时间:2017-11-28 19:16:31

标签: python multithreading python-3.x flask

我尝试实施投票系统。它的工作原理如下。如果用户投票,我会在会话变量中记录其临时状态: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()

vote.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')

1 个答案:

答案 0 :(得分:1)

不,这是不可能的。请求结束,该线程中的会话本质上是只读副本。写入它不会做任何事情,因为没有响应将更新的cookie带到浏览器。

当您存储临时投票时,将时间戳存储在临时表中会更有意义,而不是尝试使用线程和会话执行某些操作。