简体   繁体   中英

Update global dictionary/list from within an @app.route in Flask

I'm trying to find a way to update a dictionary (global) from within a function in a flask app. I want to store information about users that create an account in a dictionary like this.

user {
'key': {'key1':'value1', 'key2':'value2'}
}

But I can't seem to be able to update the dict or list from within the function. I've tried both user['key']={'key1':'value1', 'key2':'value2'} and user.update({'key': {'key1':'value1', 'key2':'value2'} methods of updating but it's not working.

This is the full code of this portion.

channel_list = []
users = {}


@app.route("/", methods=["GET", "POST"])
def index():
    username = request.form.get("username")
    firstname = request.form.get("firstname")
    lastname = request.form.get("lastname")

    if request.method == "GET":
        if session.get("user_name"):
            user_name = session.get("user_name")
            get_user = users[user_name]
            render_template("profile.html", user_name=get_user, users=users)
        else: 
            return render_template("index.html")

    if request.method == "POST":
        session["user_name"] = username
        newuser = {username: {"username": username, "firstname": firstname, "lastname": lastname}}
        users.update(newuser)
        get_user = users[username]

    return render_template("profile.html", user=get_user, users=users)     


@app.route("/signin", methods=["GET", "POST"])
def signin():


    username = request.form.get("username")

    if request.method == "GET":
        if session.get("user_name"):
            user_name = session.get("user_name")
            get_user = users[user_name]
            render_template("profile.html", user=get_user, users=users)
        else: 
            return render_template("signin.html")

    if request.method == "POST":
        session["user_name"] = username
        get_user = users[username]

        return render_template("profile.html", user=get_user, users=users)

    return render_template("signin.html")

I've figured out the problem from trying this in pure python and there, I'm also not able to update the dict without first running the function. But, how do I run each individual function (ex, index() or signin()) in flask, because I think this is the problem? I think this should be taken care of by app.run() but it's not working.

if __name__ == "__main__":
    app.run()
    socketio.run(app)

I keep getting "KeyError" each time because nothing is being inserted in the dict so there's nothing to select or access.

I'm trying to avoid using a DB and I really want to figure this out, I don't know what I'm doing wrong. The code works really well outside the flask app which is why it's frustrating.

The key error is being generated here due to this line:

if request.method == "GET":
...
    get_user = users[user_name]

This is because when you start your Flask application, initially the 'users' dictionary is empty. So when you access either of the two routes for the first time using a 'GET' method (which is the default method when you type the URL into a browser), this line here would generate a KeyError as the dictionary is empty and the key "user_name" does not exist. A common way to fix this would be to use a try-except block and handle the Exception.

Also, both of the two functions seem to be doing the same thing, ie signing the user in. It would be better if you distinguished the two functions properly. I would recommend keeping all the sign-in logic in the 'signin' route and using the 'index' route to simply display the login page. You should also set the methods of the two routes properly. Only the 'signin' function is supposed to be accessed via a POST method.

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