from pathlib import Path cases = [ ("/opt/sarex/sarex/base/tasks.py", "tasks.py", "str(TokenObtainPairSerializer.get_token(user).access_token)", 2), ("/opt/sarex/sarex/services/mixin.py", "mixin.py", "str(CustomRefreshToken.for_user(user).access_token)", 1), ] for source, destination, expression, expected in cases: original = Path(source).read_text() if original.count(expression) != expected: raise RuntimeError("JWT delegation patch does not match the application image: " + source) modified = "from config.jwt_signer_client import issue_access_token\n" + original.replace( expression, "issue_access_token(user.id)" ) compile(modified, source, "exec") Path("/jwt-patched", destination).write_text(modified)