【问题标题】:Flask remove session variable from thread烧瓶从线程中删除会话变量
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 2016-02-09
      • 2015-03-01
      • 1970-01-01
      相关资源
      最近更新 更多