When creating a user account in an application, there are a variety of data that needs to be stored for each user, as well as associated methods. The best way to store this data for a Flask application is as a model in a database managed by Flask-SQLAlchemy.
There are some fields we might want to store for each of our users no matter what kind of application we are creating. For example, these fields can include: id
, username
, email
, password_hash
, and joined_at_date
. A good way to store this data is in a User
model within your database. For example, given some database db
:
class User (db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) joined_at_date = db.Column(db.DateTime(), index=True, default=datetime.utcnow)
- here we instantiate a model
User
- that stores primary key
id
as anInteger
username
,email
andpassword_hash
asString
s, andjoined_at_date
as aDateTime
In addition to this informational data, we want to add methods that represent different user needs. We could write these methods ourselves, but Flask-Login does that work for us with the help of mixins. Mixins help us inject some standard code into a class to make life easier. In this case, we will inherit the methods and properties of the UserMixin
class.
from flask_login import UserMixin class User(UserMixin, db.Model)
- when we inherit from
UserMixin
, we inherit some of the following functions:is_active()
,is_authenticated()
,is_anonymous()
- these functions will be helpful later on for understanding the state of our users
Instructions
Let’s take it back to our dinner party application! We want to create user accounts that will allow us to store the information we need for each user interested in attending a party.
Included in app.py is the code to create a Flask application, instantiate a database db
, and begin creating a User
model.
Add the following additional attributes to the User
class:
email
, stored as a typeString
with a maximum length of 120. The column is indexable and unique.password_hash
, stored as a typeString
with a maximum length of 128.
Add one last column to the User
model joined_at
representing the date the user joined the site. The attribute should be of type DateTime
, indexable, and have a default value of datetime.utcnow
Lastly, let’s add additional functionality to our User
class by providing it the methods of the UserMixin
class.
Update User
to inherit from UserMixin
.