我制作了一个flask应用程序,它从用户那里获取和接收消息,并从我创建的Chatbot后端生成回复。当我运行app.py文件并转到本地主机时,如果我只打开一个实例,则运行良好,但是如果我尝试打开多个实例,则它们都尝试使用同一个bot。如何为每个会话创建唯一的bot。我试过使用g.bot=mybot(),但问题是每次用户回复bot时,它仍在创建一个新的bot。我对这个比较陌生,所以链接到一个详细的解释将不胜感激。注意,一些代码片段与以前的版本无关。

app = Flask(__name__)
items = ["CommonName","Title",
                      "Department","Address","City","PhoneNum"]
app.config.from_object(__name__)
bot2 = Bot2()

@app.before_request
def before_request():
    session['uid'] = uuid.uuid4()
    print(session['uid'])
    g.bot2 = Bot2()


@app.route("/", methods=['GET'])
def home():
    return render_template("index.html")

@app.route("/tables")
def show_tables():
    data = bot2.df
    if data.size == 0:
        return render_template('sad.html')
    return render_template('view.html',tables=[data.to_html(classes='df')], titles = items)

@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    bot2.input(str(userText))
    print(bot2.message)
    g.bot2.input(str(userText))
    print(g.bot2.message)
    show_tables()
    if (bot2.export):
        return (str(bot2.message) + "<br/>\nWould you like to narrow your results?")
        #return (str(bot.message) + "<a href='/tables' target=\"_blank\" style=\"color: #FFFF00\">click here</a>" + "</span></p><p class=\"botText\"><span> Would you like to narrow your results?")
    else:
        return (str(bot2.message))

if __name__ == "__main__":
    app.secret_key = 'super secret key'
    app.run(threaded=True)

最佳答案

问题:每次用户回复bot时都会创建一个新的bot
原因:app.before_request在烧瓶服务器收到每个请求之前运行。因此,每个回复都将创建一个新的Bot2实例。你可以阅读更多关于它的here
问题:为每个实例创建一个bot
可能的解决方案:我不太清楚您所说的打开多个实例是什么意思(您是试图运行同一服务器的多个实例,还是有多个ppl访问单个服务器)。我会说在Flask中读取会话并将Bot2实例作为服务器端变量存储在会话中。你可以阅读更多关于它的herehere

09-09 21:13
查看更多