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:
joined_at_date. A good way to store this data is in a
User model within your database. For example, given some database
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
- that stores primary key
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
from flask_login import UserMixin class User(UserMixin, db.Model)
- when we inherit from
UserMixin, we inherit some of the following functions:
- these functions will be helpful later on for understanding the state of our users
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
Add the following additional attributes to the
Stringwith a maximum length of 120. The column is indexable and unique.
password_hash, stored as a type
Stringwith a maximum length of 128.
Add one last column to the
joined_at representing the date the user joined the site. The attribute should be of type
DateTime, indexable, and have a default value of
Lastly, let’s add additional functionality to our
User class by providing it the methods of the
User to inherit from