Create and Encrypt User with Email and Password

  • Share this:

Code introduction


This function creates a new user record with an email and password. The password is encrypted using the generate_password_hash function from werkzeug.security.


Technology Stack : flask-sqlalchemy, SQLAlchemy, werkzeug.security

Code Type : Function

Code Difficulty : Intermediate


                
                    
def create_user_with_email_and_password(email, password):
    from flask_sqlalchemy import SQLAlchemy
    from werkzeug.security import generate_password_hash

    db = SQLAlchemy()

    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        email = db.Column(db.String(120), unique=True, nullable=False)
        password_hash = db.Column(db.String(128))

        def set_password(self, password):
            self.password_hash = generate_password_hash(password)

    new_user = User(email=email)
    new_user.set_password(password)
    db.session.add(new_user)
    db.session.commit()