Flask从线程中删除会话变量 [英] Flask remove session variable from thread

查看:87
本文介绍了Flask从线程中删除会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试实施投票系统.它的工作原理是这样的.如果用户对帖子投了票,我会在会话变量中记录其临时状态:已投票,已加星标等.

I try to implement a voting system. It works like this. If a user votes a post I record its temporary state in a session variable: upvoted, starred etc..

如果当前用户尚未投票,则将结果保存到临时表中.用户可以在5分钟内更改投票. 5分钟后,结果将使用线程永久写入数据库.

If current user hasn't voted before I save the results to temporary table. User may change the vote in 5 minutes. After 5 minutes pass the results are written to the database permanently using a thread.

我想在将结果写入数据库后清除临时会话变量.有没有办法做到这一点?

I'd like to clear temporary session variables after results are written to database. Is there a way to achieve this?

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

推荐答案

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

No, it's not possible. The request is over, the session in that thread is essentially a read-only copy. Writing to it won't do anything because there's no response to carry the updated cookie to the browser.

在存储临时投票时,将时间戳存储在临时表中比在尝试使用线程和会话做某事更有意义.

It would make more sense to store the timestamp in the temporary table when you store the temporary vote, rather than trying to do something with threads and the session.

这篇关于Flask从线程中删除会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆