Skip to content

Instantly share code, notes, and snippets.

View ShahriyarR's full-sized avatar

Shahriyar Rzayev ShahriyarR

View GitHub Profile
from pydantic import BaseModel
class DBCredentialsModel(BaseModel):
comment: str
password: Password
uri: DBUri
port: DBPort
host: DBHost
class Config:
import json
class CustomDBCredentialsEncoder(json.JSONEncoder):
def default(self, obj):
try:
# Intentionally omit other fields
return {"uri": obj.uri.get_secret()}
except AttributeError:
return super().default(obj)
@dataclass
class DBCredentials:
password: Password
uri: DBUri
port: DBPort
host: DBHost
>>> print(credentials)
DBCredentialsWithDescriptors(password=ReadOnce[secrets=*****], uri=ReadOnce[secrets=*****], port=ReadOnce[secrets=*****], host=ReadOnce[secrets=*****])
>>> credentials = DBCredentialsWithDescriptors()
>>> credentials.password.get_secret()
'db-password'
>>> credentials.password.get_secret()
...
readonce.UnsupportedOperationException: ('Not allowed on sensitive value', 'Sensitive data was already consumed')
@dataclass
class DBCredentialsWithDescriptors:
password: Password = Password("db-password")
uri: DBUri = DBUri("mysql://")
port: DBPort = DBPort(3306)
host: DBHost = DBHost("localhost")
from readonce import ReadOnce
class Password(ReadOnce):
def __init__(self, password: str) -> None:
super().__init__()
self.add_secret(password)
class DBUri(ReadOnce):
def __init__(self, uri: str) -> None:
DBPassword(password="awesome")
...
AttributeError: 'DBPassword' object has no attribute 'password'
from readonce import ReadOnce
from dataclasses import dataclass
@dataclass
class DBPassword(ReadOnce):
password: str
def __post_init__(self):
# This is going to fail with "AttributeError: 'DBPassword' object has no attribute 'password'"
self.add_secret(self.password)
>>> obj = Password(password="awesome_password")
>>> print(obj)
ReadOnce[secrets=*****]
>>> obj
ReadOnce[secrets=*****]