Skip to content

Commit

Permalink
document making secret types dumpable using the json method
Browse files Browse the repository at this point in the history
  • Loading branch information
LasseGravesen committed Mar 20, 2020
1 parent e3243d2 commit 1c2ab47
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/1328-atheuz.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
document making secret types dumpable using the json method
24 changes: 24 additions & 0 deletions docs/examples/types_secret_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class SimpleModel(BaseModel):
# Standard access methods will not display the secret
print(sm)
print(sm.password)
print(sm.dict())
print(sm.json())

# Use get_secret_value method to see the secret's content.
Expand All @@ -19,3 +20,26 @@ class SimpleModel(BaseModel):
SimpleModel(password=[1, 2, 3], password_bytes=[1, 2, 3])
except ValidationError as e:
print(e)

# If you want the secret to be dumped as plain-text using the json method,
# you can use json_encoders in the Config class.
class SimpleModelDumpable(BaseModel):
password: SecretStr
password_bytes: SecretBytes

class Config:
json_encoders = {
SecretStr: lambda v: v.get_secret_value() if v else None,
SecretBytes: lambda v: v.get_secret_value() if v else None,
}

sm2 = SimpleModelDumpable(password='IAmSensitive',
password_bytes=b'IAmSensitiveBytes')

# Standard access methods will not display the secret
print(sm2)
print(sm2.password)
print(sm2.dict())

# But the json method will
print(sm2.json())

0 comments on commit 1c2ab47

Please sign in to comment.