跨客户端的Python会话数据未分离

跨客户端的Python会话数据未分离,python,session,web-applications,flask,session-state,Python,Session,Web Applications,Flask,Session State,我正在使用pythonanywhere.com上托管的Flask在web上构建聊天机器人应用程序。但是,当多人同时与机器人聊天时,他们的问题相互干扰,机器人会在最近的问题上下文中回答 我试图使用Flask中的会话分离相关数据,但我发现了同样的问题。我阅读了文档,看到了许多使用用户名或电子邮件的示例,但在我的例子中,我想随机生成一个会话ID,然后让该用户的所有相关数据只与他们的实例相关 我知道我需要一把钥匙 我从文档和 我知道对于这些类型的应用程序,最好远离全局变量 我原以为每个浏览器请求都会自动

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

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

我知道我需要一把钥匙 我从文档和 我知道对于这些类型的应用程序,最好远离全局变量

我原以为每个浏览器请求都会自动分离会话和它们的数据,但我肯定遗漏了什么。我已经在这里发布了代码的主要部分。如果我的问题解释不清楚,您可以通过从不同浏览器与bot聊天来查看问题。非常感谢

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

谢谢你的时间&很抱歉我的问题太多了

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

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


这解决了最初的问题。

我认为您实际上的意思是顶级(模块级)变量不会在每次请求时被覆盖。这就是为什么两个浏览器使用相同的currentProfile,因此聊天被混淆了。就像他们被来自任何客户端的任何请求覆盖一样,所以聊天被混淆了,对吗?就像浏览器1一样,currentProfile会有信息“foo”,然后浏览器2会说些什么,currentProfile会变成浏览器1和浏览器2的“bar”。因此,当浏览器#1询问一个新问题时,当前配置文件仍然是“bar”,这将使机器人回答的问题与用户预期的不同。可能我使用的“request”不正确。我在网络开发方面的经验有限。看来我们可能在说同样的话。模块级变量在客户端之间共享是否更准确@康拉德