Created
September 25, 2020 19:32
-
-
Save nbrahms/2fee940f4d87f09ffc3823be5a334cf3 to your computer and use it in GitHub Desktop.
Flask SqlAlchemy engine with obfuscated string columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any | |
from typing import Optional | |
import sqlalchemy.types as types | |
from flask_sqlalchemy import SQLAlchemy | |
class ObfuscatedString(types.TypeDecorator): | |
""" | |
String column type for use with SQLAlchemy models whose | |
content should not appear in logs or exceptions | |
""" | |
impl = types.String | |
class Repr(str): | |
def __repr__(self) -> str: | |
return "********" | |
def process_bind_param(self, value: Optional[str], dialect: Any) -> Optional[Repr]: | |
return self.Repr(value) if value else None | |
def process_result_value( | |
self, value: Optional[Repr], dialect: Any | |
) -> Optional[str]: | |
return str(value) if value else None | |
db = SQLAlchemy() | |
setattr(db, "ObfuscatedString", ObfuscatedString) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment