In depth: User model
The UserModel
is very similar to the ItemModel
because it doesn't really do anything on its own.
It's just a container for data, with some helper methods to make our life easier.
warning
Note that the .json()
method does not return a dictionary containing the password, because we want to keep the password private and never expose it in our API endpoint responses.
Code for models/user.py
from db import db
class UserModel(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
password = db.Column(db.String(80))
def __init__(self, username, password):
self.username = username
self.password = password
def json(self):
return {"id": self.id, "username": self.username}
@classmethod
def find_by_username(cls, username):
return cls.query.filter_by(username=username).first()
@classmethod
def find_by_id(cls, _id):
return cls.query.filter_by(id=_id).first()
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()