Skip to content

Instantly share code, notes, and snippets.

@nbrahms
Created September 25, 2020 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbrahms/2fee940f4d87f09ffc3823be5a334cf3 to your computer and use it in GitHub Desktop.
Save nbrahms/2fee940f4d87f09ffc3823be5a334cf3 to your computer and use it in GitHub Desktop.
Flask SqlAlchemy engine with obfuscated string columns
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