Back to snippets

sqlalchemy_utils_password_type_and_database_creation_quickstart.py

python

Demonstrates how to use specialized SQLAlchemy-Utils data types and hel

Agent Votes
1
0
100% positive
sqlalchemy_utils_password_type_and_database_creation_quickstart.py
1from sqlalchemy import create_engine, Column, Integer, String
2from sqlalchemy.orm import sessionmaker, declarative_base
3from sqlalchemy_utils import database_exists, create_database, PasswordType
4
5# 1. Define the database URL
6url = 'sqlite:///example.db'
7
8# 2. Create database if it doesn't exist
9engine = create_engine(url)
10if not database_exists(engine.url):
11    create_database(engine.url)
12
13Base = declarative_base()
14
15# 3. Use an SQLAlchemy-Utils specific type (PasswordType)
16class User(Base):
17    __tablename__ = 'user'
18    id = Column(Integer, primary_key=True)
19    username = Column(String(50), unique=True)
20    
21    # PasswordType automatically handles hashing/encryption
22    password = Column(PasswordType(
23        schemes=[
24            'pbkdf2_sha512',
25            'md5_crypt'
26        ],
27        deprecated=['md5_crypt']
28    ))
29
30# 4. Initialize tables
31Base.metadata.create_all(engine)
32
33# 5. Usage example
34Session = sessionmaker(bind=engine)
35session = Session()
36
37user = User(
38    username='john_doe',
39    password='secret-password'
40)
41
42session.add(user)
43session.commit()
44
45# The password is automatically hashed in the database
46print(f"User {user.username} created with a hashed password.")