This Flask app creates a user model, saves a hashed password, and checks it. It uses an in-memory database for simplicity.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
with app.app_context():
db.create_all()
# Create user
user = User(username='bob')
user.set_password('secret123')
db.session.add(user)
db.session.commit()
# Verify password
user_check = User.query.filter_by(username='bob').first()
if user_check and user_check.check_password('secret123'):
print('Password is correct')
else:
print('Password is incorrect')