Python 跨客户端的 Flask 会话数据没有分离

Python Flask sessions data across clients is not separating

我正在使用 pythonanywhere.com 上托管的 Flask 在 Web 上构建一个聊天机器人应用程序但是,当多个人同时与机器人聊天时,他们的问题会相互干扰,而机器人会回答在最近的问题中。

我尝试在 Flask 中使用会话分离相关数据,但遇到了同样的问题。我阅读了文档并看到了许多使用用户名或电子邮件的示例,但就我而言,我想随机生成一个会话 ID,然后让该用户的所有相关数据仅与他们的实例有关。

我知道我需要 this question 的密钥 我对文档和 的一般用法有基本的了解 而且我知道最好远离这些类型的应用程序的全局变量 from this question

我以为每个浏览器请求都会自动分离会话及其数据,但我一定遗漏了一些东西。我已经在此处发布了代码的主要部分。如果我的问题解释不清楚,您可以在 youngblksocrates.pythonanywhere.com 通过与来自不同浏览器的机器人聊天来查看问题。非常感谢!

from flask import Flask, request, url_for, render_template, session
import random
from user_info_object import UserInfo
from script_freeStyle import FreeStyleXXXX
import simplejson as json

app = Flask(__name__)
app.secret_key = "my secret key"

currentProfile = UserInfo() #helps bot know what the user has asked
learnBoutClass = FreeStyleXXXX() #conversation script to follow


greetings = ["HI","HEY","GREETINGS","HELLO","WASSUP", "WHAT UP"]

def preprocess(textblob):
    return str(textblob.correct())
def bot_reply_to_this(input,scriptobj):

    if input.upper() in greetings:
        reply = random.choice(["Hello!", "Hi", "Hey", "Greetings", "*Waves*","What's up?"])
    else:

        currentProfile = UserInfo()
        myspecificprofile = currentProfile.populate(session['profilestate'])
        responseAndProfile = scriptobj.determineReply(myspecificprofile,input)
        response = responseAndProfile[0]
        updatedprofile = responseAndProfile[1]
        session['lastrequestedinfo'] = scriptobj.lastRequestedInfo
        session['profilestate'] = json.dumps(updatedprofile.__dict__)
    return response

@app.route('/')
def user_chat_begins_fresh():

    sessionID = ''.join(random.choice('0123456789ABCDEF') for i in range(16))
    session.pop('ID',None)
    session['ID'] = sessionID
    session['lastrequestedinfo'] = ""
    #everything gotta start fresh
    takeClassScript.lastRequestedInfo = ""
    learnBoutClass.lastRequestedInfo = ""
    #create a new profile so that the state resets
    currentProfile = UserInfo()
    session['profilestate'] = json.dumps(currentProfile.__dict__)
    del chathistory [:]
    return render_template('init.html',urlToConversation=url_for('conversation_container'),inputVarName="input")

@app.route('/reply', methods=['POST'])
def conversation_container():
    rawinput = request.form["input"]
    session['input'] = rawinput
    blob_input = TextBlob(session['input'])
    cleaned_input = session['input']
    chosenscript = learnBoutClass
    session['lastrequestedinfo'] = chosenscript.lastRequestedInfo
    session['reply'] = bot_reply_to_this(session['input'],chosenscript)
    chathistory.append("You: " + session['input'] + "\n" )
    chathistory.append("Bot: " + session['reply'] + "\n" )
    printedhistory = "\n".join(chathistory)
    session['history'] = printedhistory

    return render_template('conversation.html',\
        output=session['history'] ,\
        urlToConversation=url_for('conversation_container'),\
        inputVarName="input",\
        urlToFreshChat=url_for('user_chat_begins_fresh'))

感谢您抽出宝贵时间,很抱歉提出冗长的问题!

我四处询问,发现 如果文件的顶层有变量,那么它们会在每次请求时被覆盖

由于数据存储在 currentProfilelearnBoutClass 变量中,我从顶层删除了这些变量,并将它们替换为会话字典中的变量:session['profiledata']session['scriptdata']

这解决了最初的问题。