article

Friday, October 16, 2020

Simple Flask Login

Simple Flask Login
Flask-Login module It provides user session management for Flask: logging in, logging out, and remembering session. 

The module stores the user ID, restricts views to logged in users, protects cookies and has many other features.
https://flask-login.readthedocs.io/en/latest/
app.py
from flask import Flask, redirect
from flask_sqlalchemy import SQLAlchemy 
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
#ModuleNotFoundError: No module named 'flask_sqlalchemy' = (venv) C:\flaskmyproject>pip install Flask-SQLAlchemy
#ModuleNotFoundError: No module named 'flask_login' = (venv) C:\flaskmyproject>pip install flask_login

#import sqlite3
 
app = Flask(__name__)
#conn = sqlite3.connect('flask_login.db')
#print("Opened database successfully");

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flask_login.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30), unique=True)
	
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@login_manager.unauthorized_handler
def unauthorized_callback():
    return redirect('/login')
	
@app.route('/')
def index():
    return 'Public Page'
	
@app.route('/login')
def login():
    user = User.query.filter_by(username='cairocoders').first()
    login_user(user)
    return 'You are now logged in!'	
	
@app.route('/home')
@login_required
def home():
    return 'The current user is ' + current_user.username 	

@app.route('/profile')
@login_required
def profile():
    return 'profile page'
	
@app.route('/logout')
@login_required
def logout():
    logout_user()
    return 'You are now logged out!'
	
if __name__ == '__main__':
 app.run(debug=True)
 

Related Post