Skip to content

Commit

Permalink
Add support for redaction
Browse files Browse the repository at this point in the history
  • Loading branch information
hugorodgerbrown committed Sep 17, 2023
1 parent 6379cea commit b56fbdb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
18 changes: 18 additions & 0 deletions anonymiser/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,21 @@ def post_anonymise_object(
"""
pass

def collect_redactions(self) -> dict[str, Any]:
"""
Return a dict of field names to redaction functions.
This is used by the redact_queryset method to redact fields that
support redaction. Each value can be a static value or a callable,
such as a function (e.g. F expression) or a class (e.g. Func).
"""
return {
f.name: getattr(self, f"redact_{f.name}")
for f in self.get_model_fields()
if hasattr(self, f"redact_{f.name}")
}

def redact_queryset(self, queryset: models.QuerySet[models.Model]) -> int:
return queryset.update(**self.collect_redactions())
14 changes: 14 additions & 0 deletions tests/anon.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from django.db import models
from django.db.models.functions import Concat

from anonymiser.db.expressions import GenerateUuid4
from anonymiser.decorators import register_anonymiser
from anonymiser.models import BaseAnonymiser

Expand All @@ -8,6 +12,16 @@
class UserAnonymiser(BaseAnonymiser):
model = User

redact_first_name = "FIRST_NAME"
redact_last_name = "LAST_NAME"
redact_uuid = GenerateUuid4()
redact_email = Concat(
models.F("first_name"),
models.Value("."),
models.F("last_name"),
models.Value("@example.com"),
)

def anonymise_first_name(self, obj: User) -> None:
obj.first_name = "Anonymous"

Expand Down

0 comments on commit b56fbdb

Please sign in to comment.