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



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

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

我知道我需要这个问题的密钥我从文档和其他问题中基本了解了一般用法我知道对于这些类型的应用程序,最好远离全局变量

我以为每个浏览器请求都会自动将会话及其数据分开,但我一定遗漏了什么。我已经在这里发布了代码的主要部分。如果我的问题解释不清楚,你可以通过与不同浏览器的机器人聊天,在youngblksocrates.pythonnywhere.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']

这解决了最初的问题。

最新更新