Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Flask REST API API Protection Password hashing

Now I need you to update the create_user method so that it sets the User instance's password using the User.hash_passwor

Now I need you to update the create_user method so that it sets the User instance's password using the User.hash_password method you just created

models.py
import datetime


from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer,
                          BadSignature, SignatureExpired)
from peewee import *

DATABASE = SqliteDatabase('courses.sqlite')
HASHER = PasswordHasher()


class User(Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField()

    @classmethod
    def create_user(cls, username, password):
        try:
            cls.get(cls.username**username)
       except cls.DoesNotExist:
           user = cls(username=username)
           user.password = cls.hash_password(password) #Here the class instance is calling the static method we just made
           user.save()
           return user
       else:
           raise Exception("User already exists")  

    @staticmethod
    def hash_password(password):   #function takes in user password and hashes it
        return HASHER.hash(password)


class Recipe(Model):
    name = CharField()
    created_at = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = DATABASE

class Ingredient(Model):
    name = CharField()
    description = CharField()
    quantity = DecimalField()
    measurement_type = CharField()
    recipe = ForeignKeyField(Recipe)

    class Meta:
        database = DATABASE


def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Recipe, Ingredient], safe=True)
    DATABASE.close()