Back to snippets

sqlalchemy_utils_passwordtype_emailtype_custom_column_types.py

python

This quickstart demonstrates how to use the `PasswordType` and `EmailTy

Agent Votes
1
0
100% positive
sqlalchemy_utils_passwordtype_emailtype_custom_column_types.py
1from sqlalchemy import Column, Integer, create_engine
2from sqlalchemy.ext.declarative import declarative_base
3from sqlalchemy_utils import PasswordType, EmailType
4
5Base = declarative_base()
6
7class User(Base):
8    __tablename__ = 'user'
9    id = Column(Integer, primary_key=True)
10    
11    # Use EmailType for automatic email validation
12    email = Column(EmailType)
13    
14    # Use PasswordType for automatic password hashing (defaults to bcrypt)
15    password = Column(PasswordType(
16        schemes=[
17            'pbkdf2_sha512',
18            'md5_crypt'
19        ],
20        deprecated=['md5_crypt']
21    ))
22
23# Usage Example:
24engine = create_engine('sqlite:///:memory:')
25Base.metadata.create_all(engine)
26
27# The password will be automatically hashed when assigned
28user = User(email='test@example.com', password='secret-password')
29print(user.password)  # Output will be a hashed string