User authentication and session management for Flask.
Low maintenance activity. Last release over 3 years ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install flask-loginFlask-Login
Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering your users' sessions over extended periods of time.
Flask-Login is not bound to any particular database system or permissions model. The only requirement is that your user objects implement a few methods, and that you provide a callback to the extension capable of loading users from their ID.
Installation
Install the extension with pip:
$ pip install flask-login
Usage
Once installed, the Flask-Login is easy to use. Let's walk through setting up a basic application. Also please note that this is a very basic guide: we will be taking shortcuts here that you should never take in a real application.
To begin we'll set up a Flask app:
import flask
app = flask.Flask(__name__)
app.secret_key = 'super secret string' # Change this!
Flask-Login works via a login manager. To kick things off, we'll set up the login manager by instantiating it and telling it about our Flask app:
import flask_login
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
To keep things simple we're going to use a dictionary to represent a database of users. In a real application, this would be an actual persistence layer. However it's important to point out this is a feature of Flask-Login: it doesn't care how your data is stored so long as you tell it how to retrieve it!
# Our mock database.
users = {'foo@bar.tld': {'password': 'secret'}}
We also need to tell Flask-Login how to load a user from a Flask request and
from its session. To do this we need to define our user object, a
user_loader callback, and a request_loader callback.
class User(flask_login.UserMixin):
pass
@login_manager.user_loader
def user_loader(email):
if email not in users:
return
user = User()
user.id = email
return user
@login_manager.request_loader
def request_loader(request):
email = request.form.get('email')
if email not in users:
return
user = User()
user.id = email
return user