You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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).
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.
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:
0 commit comments