我正在使用在pythonanywhere.com上托管的Flask在网上构建聊天机器人应用程序但是,当不止一个人同时与机器人聊天时,他们的问题会相互干扰并且机器人在上下文中回答最近的一个问题。
我尝试使用Flask中的会话分离相关数据,但我看到了同样的问题。我阅读了文档并看过许多使用用户名或电子邮件的示例,但在我的情况下,我想随机生成会话ID,然后让该用户的所有相关数据仅与其实例相关。
我知道我需要来自this question的密钥 我对文档和other questions的一般用法有基本的了解 我知道最好远离这些类型的应用程序的全局变量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'))
感谢您的时间和抱歉这个罗嗦的问题!
答案 0 :(得分:0)
我四处询问并发现如果文件的顶层有变量,那么每次请求都会覆盖它们。
由于数据存储在currentProfile
和learnBoutClass
变量中,我从顶层删除了这些变量,并将其替换为会话字典中的变量:session['profiledata']
和session['scriptdata']
这解决了最初的问题。