简体   繁体   English

在Flask中创建Python类的多个实例

[英]Creating Multiple Instances of Python Class in Flask

I have made a flask application which gets and receives messages from the user and generates a reply from a Chatbot backend I have created. 我做了一个烧瓶应用程序,它从用户获取和接收消息,并从我创建的Chatbot后端生成回复。 When I run my my app.py file and I go to my localhost it runs fine if I only open one instance, however if I try to open multiple instances then they all try to use the same bot. 当我运行我的app.py文件并转到我的localhost时,如果我只打开一个实例,它运行正常,但是如果我尝试打开多个实例,那么它们都会尝试使用相同的机器人。 How do I create a unique bot for each session. 如何为每个会话创建一个独特的bot。 I tried using g.bot = mybot() but the problem was it still kept creating a new bot each time the user replied to the bot. 我尝试使用g.bot = mybot(),但问题是每次用户回复机器人时它仍然会继续创建一个新机器人。 I am relatively new to this so links to a detailed explanation would be appreciated. 我对此比较陌生,所以我们将非常感谢您对详细解释的链接。 Note some pieces of code are unrelated junk from previous versions. 请注意,某些代码段与先前版本中的无关垃圾。

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)

Problem: A new bot is created each time the user replies to the bot 问题:每次用户回复机器人时都会创建一个新机器人

Reason: app.before_request runs before each request that your flask server receives. 原因: app.before_request在您的烧瓶服务器收到的每个请求之前运行。 Hence each reply will create a new Bot2 instance. 因此,每个回复将创建一个新的Bot2实例。 You can read more about it here . 你可以在这里阅读更多相关信息。

Problem: Creating a bot per instance 问题:为每个实例创建一个bot

Possible Solution: I'm not really sure what you mean by opening multiple instances (are you trying to run multiple instances of the same server, or there are multiple ppl accessing the single server). 可能的解决方案:我不确定你打开多个实例是什么意思(你试图运行同一服务器的多个实例,还是有多个ppl访问单个服务器)。 I would say to read up on Sessions in Flask and store a Bot2 instance inside sessions as a server side variable. 我会说要读取Flask中的Sessions并将会话中的Bot2实例存储为服务器端变量。 You can read more about it here and here . 你可以在这里这里阅读更多相关信息。

You could try assigning the session id from flask-login to the bot instead of creating a unique id at before request. 您可以尝试将会话ID从flask-login分配给机器人,而不是在请求之前创建唯一ID。 Right now, like @Imma said, a new bot is created for every request. 就像@Imma所说的那样,每个请求都会创建一个新的机器人。

You will have to store an array of classes. 您将必须存储一组类。 When a session is created, ie, a user or an anonymous user logs in, a bot/class instance gets created and is pushed onto the array. 创建会话时,即用户或匿名用户登录时,会创建机器人/类实例并将其推送到阵列上。

You can keep the array in the session object... do note that the session object will get transferred in the form of a cookie to the front end... so you may be potentially exposing all the chat sessions...Also, a lot of users will unnecessarily slow down the response. 您可以将数组保留在会话对象中...请注意会话对象将以cookie的形式传输到前端...因此您可能会暴露所有聊天会话...此外,很多用户会不必要地减慢响应速度。

Another alternative is to create a separate container and run the bot as a separate microservice rather than integrate it with your existing flask application (this is what we ended up doing) 另一种方法是创建一个单独的容器并将机器人作为单独的微服务运行,而不是将其与现有的烧瓶应用程序集成(这是我们最终做的)

删除行bot2 = Bot2() ,并将所有对bot2的引用bot2g.bot2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM