My question is why does the return statement at the end of the sign up return the value of .is-authenticated property to be True ? I believed that the login_user() function sets the property to be True (which obviously hasn’t been called yet). It would be much appreciated if someone could clarify the above doubt and explain the processes that take place internally when the above code is run.
from flask import Flask,render_template,redirect,url_for,request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager,UserMixin,login_user,logout_user,login_required,current_user
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.secret_key = 'secret_key'
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
class Users(UserMixin,db.Model):
id = db.Column(db.Integer, primary_key = True, autoincrement = True)
first_name = db.Column(db.String, nullable = False)
email = db.Column(db.String, nullable = False)
username = db.Column(db.String, unique = True, nullable = False)
password = db.Column(db.String, nullable = False)
@login_manager.user_loader
def load_user(id):
return db.session.query(Users).get(id)
@app.route('/', methods=['GET','POST'])
def login():
if(request.method == 'GET'):
return render_template('index.html')
else:
data = request.form
user = db.session.query(Users).filter_by(username=data['username']).first()
if(user):
if(user.password == data['password']):
login_user(user)
return redirect(url_for('home',username=current_user.username))
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
@app.route('/sign_up',methods = ['GET','POST'])
def sign_up():
if(request.method == 'GET'):
return render_template('sign_up.html')
else:
data = request.form
user = db.session.query(Users).filter_by(username=data['username']).first()
if(user):
return redirect(url_for('sign_up'))
else:
new_user = Users(first_name = data['first_name'],email = data['email'],username = data['username'],password = data['password'])
db.session.add(new_user)
db.session.commit()
return str(new_user.is_authenticated)
# return redirect(url_for('login'))
@app.route('/home/<username>',methods=['GET','POST'])
@login_required
def home(username):
return render_template('home.html',username=username)
@app.route('/logout',methods = ['GET','POST'])
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)