[英]Creating Multiple Instances of Python Class in Flask
我做了一個燒瓶應用程序,它從用戶獲取和接收消息,並從我創建的Chatbot后端生成回復。 當我運行我的app.py文件並轉到我的localhost時,如果我只打開一個實例,它運行正常,但是如果我嘗試打開多個實例,那么它們都會嘗試使用相同的機器人。 如何為每個會話創建一個獨特的bot。 我嘗試使用g.bot = mybot(),但問題是每次用戶回復機器人時它仍然會繼續創建一個新機器人。 我對此比較陌生,所以我們將非常感謝您對詳細解釋的鏈接。 請注意,某些代碼段與先前版本中的無關垃圾。
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)
您可以嘗試將會話ID從flask-login分配給機器人,而不是在請求之前創建唯一ID。 就像@Imma所說的那樣,每個請求都會創建一個新的機器人。
您將必須存儲一組類。 創建會話時,即用戶或匿名用戶登錄時,會創建機器人/類實例並將其推送到陣列上。
您可以將數組保留在會話對象中...請注意會話對象將以cookie的形式傳輸到前端...因此您可能會暴露所有聊天會話...此外,很多用戶會不必要地減慢響應速度。
另一種方法是創建一個單獨的容器並將機器人作為單獨的微服務運行,而不是將其與現有的燒瓶應用程序集成(這是我們最終做的)
刪除行bot2 = Bot2()
,並將所有對bot2
的引用bot2
為g.bot2
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.