简体   繁体   中英

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. 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. How do I create a unique bot for each session. 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. 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. Hence each reply will create a new Bot2 instance. You can read more about it here .

Problem: Creating a bot per instance

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). I would say to read up on Sessions in Flask and store a Bot2 instance inside sessions as a server side variable. 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. Right now, like @Imma said, a new bot is created for every request.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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