Flask me how to Login!
Many applications and websites need a way to keep track of and coordinate session and user information on the back end. While there are a plethora of ways to implement these features, Flask-Login easily provides us with the most important. The examples routes I'll be showing use flask-RESTful to organize the api, and I'll be showing as simple an implementation as I can manage. Let's take a look. First, we install: $ pip install flask-login Next, we'll import and create our LoginManager class, then initialize it with our app, assuming that we're using a config file: # config.py from flask_login import LoginManager login_manager = LoginManager() login_manager.init_app(app) Our app.py imports: # app.py from flask_login import login_user, logout_user, current_user from config import app, db, api, login_manager from models import User That's a lot of imports! Let's break them down: login_user is a function that takes a user and stores them as the current_user and adds their id to the session. logout_user clears the current_user and cleans up relevant cookies from the session. We'll also need provide a user_loader callback to pull the user from our database based on the id stored in session. We don't have to interact with this function directly after it's implemented. @login_manager.user_loader def load_user(user_id): return User.get(user_id) We also have to provide the corresponding class method in our model: # models.py from flask_login import UserMixin class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String, unique=True, nullable=False) password = db.Column(db.String, nullable=False) @classmethod def get(self, id): return User.query.get(id) You may have noticed we're inheriting from UserMixin as well. Flask-login requires your model to have the following properties and methods: def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return str(self.id) While you can overwrite these, UserMixin allows you to shortcut including these by providing default implementations if you don't need the extra functionality. Back in our app.py we can take a look at handling request to log in: class Login(Resource): def post(self): data = request.json user = User.query.filter_by(username=data.get("username")).first() if user is None or not user.authenticate(data.get("password")): response = make_response({'error':'Invalid username or ID'}) response.status_code = 401 return response login_user(user) return make_response(user.to_dict(), 201) The call to login_user is the magic here, this will store the id of the user that was passed to us in session so that we can easily authenticate and reload the user on a page refresh, as well as set the current_user to the user passed. We'll return a copy of the user so our front-end can log in too. Our logout is even simpler: class Logout(Resource): def get(self): logout_user() return make_response('logout successful', 200) logout_user will clear our the current user's id from session and the current_user object. We'll return a simple message for our front end. And that's it! Flask-login includes many more features than these but this should get you off the ground if you just need a basic login management system.

Many applications and websites need a way to keep track of and coordinate session and user information on the back end. While there are a plethora of ways to implement these features, Flask-Login easily provides us with the most important. The examples routes I'll be showing use flask-RESTful to organize the api, and I'll be showing as simple an implementation as I can manage. Let's take a look.
First, we install:
$ pip install flask-login
Next, we'll import and create our LoginManager class, then initialize it with our app, assuming that we're using a config file:
# config.py
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
Our app.py imports:
# app.py
from flask_login import login_user, logout_user, current_user
from config import app, db, api, login_manager
from models import User
That's a lot of imports! Let's break them down: login_user is a function that takes a user and stores them as the current_user and adds their id to the session. logout_user clears the current_user and cleans up relevant cookies from the session.
We'll also need provide a user_loader callback to pull the user from our database based on the id stored in session. We don't have to interact with this function directly after it's implemented.
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
We also have to provide the corresponding class method in our model:
# models.py
from flask_login import UserMixin
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
@classmethod
def get(self, id):
return User.query.get(id)
You may have noticed we're inheriting from UserMixin as well. Flask-login requires your model to have the following properties and methods:
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return str(self.id)
While you can overwrite these, UserMixin allows you to shortcut including these by providing default implementations if you don't need the extra functionality.
Back in our app.py we can take a look at handling request to log in:
class Login(Resource):
def post(self):
data = request.json
user = User.query.filter_by(username=data.get("username")).first()
if user is None or not user.authenticate(data.get("password")):
response = make_response({'error':'Invalid username or ID'})
response.status_code = 401
return response
login_user(user)
return make_response(user.to_dict(), 201)
The call to login_user is the magic here, this will store the id of the user that was passed to us in session so that we can easily authenticate and reload the user on a page refresh, as well as set the current_user to the user passed. We'll return a copy of the user so our front-end can log in too.
Our logout is even simpler:
class Logout(Resource):
def get(self):
logout_user()
return make_response('logout successful', 200)
logout_user will clear our the current user's id from session and the current_user object. We'll return a simple message for our front end.
And that's it! Flask-login includes many more features than these but this should get you off the ground if you just need a basic login management system.