Bootstrap FreeKB - Flask - Create secure password using generate_password_hash
Flask - Create secure password using generate_password_hash

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your Flask app has the following structure.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

Here is a super basic example of how werkzeug.security generate_password_hash can be used to generate an encrypted password, which should produce something like this:

  • scrypt:32768:8:1$PttnjU5XWD8cKvuB$92146e6527afb300d4ab61dbdd8e2dd9f8b58b42f8f97fb6766c4d673d34cc200b36340ced859517cf1248e80b31d7308f20b8fddc021151bb79eece83c58cae
from flask import Blueprint
from . import app
from werkzeug.security import generate_password_hash

views = Blueprint('views', __name__)

@views.route('/')
def home():

    password = generate_password_hash('itsasecret', method='scrypt')

    print(f"password = {password}")

    return "success!"

 

Often, the logic for the initial setup of the database is placed in the controller (__init__.py). The create_all function will:

  • Create the example.db file if it doesn't exist
  • Create the tables in models.py if they don't exist
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def app_obj():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.init_app(app)

    with app.app_context():
        db.create_all()
        print("Created example.db SQLLite Database")

    return app

 

Let's say your model (models.py in this example) contains the following. In this example, the name of the table will be "users". Notice there is a "password" column.

from . import db
from sqlalchemy import func, select

class users(db.Model):
    id           = db.Column(db.Integer,     nullable=False, unique=True, primary_key=True)
    date_created = db.Column(db.DateTime(timezone=True), default=func.now())
    date_updated = db.Column(db.DateTime(timezone=True), onupdate=func.now())     
    email        = db.Column(db.String(100), nullable=False, unique=True)
    password     = db.Column(db.String(200), nullable=False, unique=False)

 

werkzeug.security can be used to generate_password_hash and check_password_hash. This should create a record in the table where the password is hashed.

from flask import Blueprint, render_template
from werkzeug.security import generate_password_hash

views = Blueprint('views', __name__)

@views.route('/')
def home():
    data = users(
        username='john.doe',
        password=generate_password_hash('itsasecret', method='scrypt'),
        date_updated=func.now()
    )
    db.session.add(data)
    db.session.commit()
    return render_template('home.html')

 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 5ce371 in the box below so that we can be sure you are a human.