简体   繁体   中英

Flask->Is there any other way of using the login_user of flask_login without comitting to a database?

I've noticed that whenever I use login_user it gives me 401-Unauthorized if before this I haven't added the said User to the database. Is there a way to use login_user without adding the user to the database and without the 401-Unauthorized?? Here's my function where it all happens

@app.route('/Index', methods=['GET', 'POST'])
def Index():
    if request.method=='POST':
        New_Username = request.form['Username']
        New_Password = request.form['Password']
        user = bool(Users.query.filter_by(Username=New_Username).first())
        if user is not None and user == False:
            New_User = Users(Username=New_Username, Password=New_Password)
            db.session.add(New_User)
            db.session.commit()
            login_user(New_User)
            print('Works')
            return redirect('/Dashboard')
        else:
            New_User = Users(Username=New_Username, Password=New_Password)
            login_user(New_User)
            print('Doesnt work')
            return redirect('/Dashboard')
    else:
        return render_template('Index.html', New_User=All_Users)

No. login_user needs a User class entity.

Your use of capital letters is unconventional and may cause obscure problems. For one, does your Users class have uppercase params? Usually, username and password are lowercase.

And, no need for the bool .

Here is more conventional casing, standard User model, etc.:

from django.contrib.auth.models import User

@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method=='POST':
        new_username = request.form['username']
        new_password = request.form['password']
        user = User.query.filter_by(username=new_username).first()
        if not user:
            new_user = User(username=new_username, password=new_password)
            new_user.save()
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user)
            print('Works')
            return redirect('/dashboard')
        else:
            login_user(user)
            print('Doesnt work')
            return redirect('/dashboard')
    else:
        # All_Users not defined!
        return render_template('index.html', new_user=All_Users)

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