Skip to content

Commit b5092e2

Browse files
committed
feat: Add tutorial and advanced page for EncryptedType
1 parent c6acc1f commit b5092e2

File tree

6 files changed

+227
-0
lines changed

6 files changed

+227
-0
lines changed

docs/advanced/encrypted-type.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Encrypted Type
2+
3+
Sometimes you need to store sensitive data like secrets, tokens, or personal information in your database in an encrypted format.
4+
5+
You can use the `EncryptedType` from the `sqlalchemy-utils` package to achieve this with SQLModel.
6+
7+
## A Model with an Encrypted Field
8+
9+
You can define a field with `EncryptedType` in your SQLModel model using `sa_column`:
10+
11+
{* ./docs_src/advanced/encrypted_type/tutorial001.py *}
12+
13+
In this example, the `secret_name` field will be automatically encrypted when you save a `Hero` object to the database and decrypted when you access it.
14+
15+
/// tip
16+
For this to work, you need to have `sqlalchemy-utils` and `cryptography` installed.
17+
///
18+
19+
For a more detailed walkthrough, including how to create and query data with encrypted fields, check out the [Encrypting Data Tutorial](../tutorial/encrypted-type.md).

docs/tutorial/encrypted-type.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Encrypting Data
2+
3+
In this tutorial, you'll learn how to encrypt data before storing it in your database using SQLModel and `sqlalchemy-utils`.
4+
5+
## The Scenario
6+
7+
Let's imagine we're building an application to store information about characters from our favorite TV show, Ted Lasso. We want to store their names, secret names (which should be encrypted), and their ages.
8+
9+
## The Code
10+
11+
Here's the complete code to achieve this:
12+
13+
{* ./docs_src/tutorial/encrypted_type/tutorial001.py *}
14+
15+
### Understanding the Code
16+
17+
Let's break down the key parts of the code:
18+
19+
1. **`EncryptedType`**: We use `EncryptedType` from `sqlalchemy-utils` as a `sa_column` for the `secret_name` field. This tells SQLModel to use this special type for the column in the database.
20+
21+
2. **Encryption Key**: We provide an encryption key to `EncryptedType`. In a real-world application, you should **never** hardcode the key like this. Instead, you should load it from a secure source like a secret manager or an environment variable.
22+
23+
3. **`demonstrate_encryption` function**: This function shows the power of `EncryptedType`.
24+
* First, it queries the database directly using raw SQL. When we print the `secret_name` from this query, you'll see the encrypted string, not the original secret name.
25+
* Then, it queries the database using SQLModel. When we access the `secret_name` attribute of the `Character` objects, `EncryptedType` automatically decrypts the data for us, so we get the original, readable secret names.
26+
27+
## How to Test
28+
29+
To run this example, first create a virtual environment:
30+
31+
```bash
32+
python -m venv venv
33+
source venv/bin/activate
34+
```
35+
36+
Then, install the required packages from the `requirements.txt` file:
37+
38+
```bash
39+
pip install -r docs_src/tutorial/encrypted_type/requirements.txt
40+
```
41+
42+
Then, you can run the python script:
43+
44+
```bash
45+
python docs_src/tutorial/encrypted_type/tutorial001.py
46+
```
47+
48+
## Running the Code
49+
50+
When you run the code, you'll see the following output:
51+
52+
```console
53+
Creating database and tables...
54+
Creating characters...
55+
56+
Demonstrating encryption...
57+
Data as stored in the database:
58+
Name: Roy Kent, Encrypted Secret Name: b'5dBrkurIL+fEin+1eUBc0A=='
59+
Name: Jamie Tartt, Encrypted Secret Name: b'CDLkQWx5ezXn+U4kRlVFyQ=='
60+
Name: Dani Rojas, Encrypted Secret Name: b'SqSjH+biJttbs9zH+DBw8A=='
61+
62+
Data as accessed through SQLModel:
63+
Name: Roy Kent, Decrypted Secret Name: The Special One
64+
Name: Jamie Tartt, Decrypted Secret Name: Baby Shark
65+
Name: Dani Rojas, Decrypted Secret Name: Fútbol is Life
66+
```
67+
68+
As you can see, `EncryptedType` handles the encryption and decryption for you automatically, making it easy to store sensitive data securely.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
import os
3+
from typing import Optional
4+
5+
import sqlalchemy
6+
from sqlalchemy import Column
7+
from sqlalchemy_utils import EncryptedType
8+
from sqlalchemy_utils.types.encrypted.encrypted_type import AesEngine
9+
from sqlmodel import create_engine, Field, Session, SQLModel
10+
11+
12+
# For a real application, use a securely managed key
13+
ENCRYPTION_KEY = "a-super-secret-key"
14+
15+
class Hero(SQLModel, table=True):
16+
id: Optional[int] = Field(default=None, primary_key=True)
17+
name: str
18+
# Because the secret name should stay a secret
19+
secret_name: str = Field(
20+
sa_column=Column(
21+
EncryptedType(
22+
sqlalchemy.Unicode,
23+
ENCRYPTION_KEY,
24+
AesEngine,
25+
"pkcs5",
26+
)
27+
)
28+
)
29+
age: Optional[int] = None
30+
31+
32+
sqlite_file_name = "database.db"
33+
sqlite_url = f"sqlite:///{sqlite_file_name}"
34+
35+
engine = create_engine(sqlite_url)
36+
37+
38+
def create_db_and_tables():
39+
SQLModel.metadata.create_all(engine)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
sqlmodel
2+
sqlalchemy-utils
3+
cryptography
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Import necessary modules
2+
import os
3+
from typing import Optional
4+
5+
import sqlalchemy
6+
from sqlalchemy import Column, text
7+
from sqlalchemy_utils import EncryptedType
8+
from sqlalchemy_utils.types.encrypted.encrypted_type import AesEngine
9+
from sqlmodel import create_engine, Field, Session, SQLModel, select
10+
11+
# Define a secret key for encryption.
12+
# In a real application, this key should be stored securely and not hardcoded.
13+
# For example, you could load it from an environment variable or a secret management service.
14+
ENCRYPTION_KEY = "a-super-secret-key"
15+
16+
# Define the Character model
17+
# This model represents a table named 'character' in the database.
18+
class Character(SQLModel, table=True):
19+
id: Optional[int] = Field(default=None, primary_key=True)
20+
name: str
21+
# The secret_name field is encrypted in the database.
22+
# We use EncryptedType from sqlalchemy-utils for this.
23+
secret_name: str = Field(
24+
sa_column=Column(
25+
EncryptedType(
26+
sqlalchemy.Unicode,
27+
ENCRYPTION_KEY,
28+
AesEngine,
29+
"pkcs5",
30+
)
31+
)
32+
)
33+
age: Optional[int] = None
34+
35+
# Define the database URL and create the engine
36+
# We are using a SQLite database for this example.
37+
sqlite_file_name = "database.db"
38+
sqlite_url = f"sqlite:///{sqlite_file_name}"
39+
engine = create_engine(sqlite_url)
40+
41+
# This function creates the database and the Character table.
42+
# It first drops the existing table to ensure a clean state for the example.
43+
def create_db_and_tables():
44+
SQLModel.metadata.drop_all(engine)
45+
SQLModel.metadata.create_all(engine)
46+
47+
# This function creates some sample characters and adds them to the database.
48+
def create_characters():
49+
# Create instances of the Character model
50+
roy_kent = Character(name="Roy Kent", secret_name="The Special One", age=40)
51+
jamie_tartt = Character(name="Jamie Tartt", secret_name="Baby Shark", age=25)
52+
dani_rojas = Character(name="Dani Rojas", secret_name="Fútbol is Life", age=23)
53+
54+
# Use a session to interact with the database
55+
with Session(engine) as session:
56+
# Add the characters to the session
57+
session.add(roy_kent)
58+
session.add(jamie_tartt)
59+
session.add(dani_rojas)
60+
61+
# Commit the changes to the database
62+
session.commit()
63+
64+
# This function demonstrates how the encryption works.
65+
def demonstrate_encryption():
66+
with Session(engine) as session:
67+
# Query the database directly to see the encrypted data
68+
# We use a raw SQL query for this.
69+
statement = text("SELECT name, secret_name FROM character")
70+
results = session.exec(statement).all()
71+
print("Data as stored in the database:")
72+
for row in results:
73+
# The secret_name will be an encrypted string.
74+
print(f"Name: {row.name}, Encrypted Secret Name: {row.secret_name}")
75+
76+
# Query through SQLModel to see the decrypted data
77+
# SQLModel will automatically decrypt the secret_name.
78+
statement = select(Character)
79+
characters = session.exec(statement).all()
80+
print("\nData as accessed through SQLModel:")
81+
for character in characters:
82+
# The secret_name will be the original, decrypted string.
83+
print(f"Name: {character.name}, Decrypted Secret Name: {character.secret_name}")
84+
85+
# The main function that runs the example.
86+
def main():
87+
print("Creating database and tables...")
88+
create_db_and_tables()
89+
print("Creating characters...")
90+
create_characters()
91+
print("\nDemonstrating encryption...")
92+
demonstrate_encryption()
93+
94+
# Run the main function when the script is executed.
95+
if __name__ == "__main__":
96+
main()

mkdocs.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ nav:
8787
- tutorial/limit-and-offset.md
8888
- tutorial/update.md
8989
- tutorial/delete.md
90+
- tutorial/encrypted-type.md
9091
- Connect Tables - JOIN:
9192
- tutorial/connect/index.md
9293
- tutorial/connect/create-connected-tables.md
@@ -128,6 +129,7 @@ nav:
128129
- advanced/index.md
129130
- advanced/decimal.md
130131
- advanced/uuid.md
132+
- advanced/encrypted-type.md
131133
- Resources:
132134
- resources/index.md
133135
- help.md

0 commit comments

Comments
 (0)