django-field-logger 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Sergio Rodríguez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include LICENSE
2
+ include README.md
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: django-field-logger
3
+ Version: 0.0.1
4
+ Summary: A python package which logs each change made to a Django model instance.
5
+ Home-page: https://github.com/nibblex/django-field-logger
6
+ Author: Sergio Rodríguez
7
+ Author-email: srodriguez3441@gmail.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ License-File: LICENSE
@@ -0,0 +1,2 @@
1
+ # django-field-logger
2
+ A python package which logs each change made to a Django model instance.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: django-field-logger
3
+ Version: 0.0.1
4
+ Summary: A python package which logs each change made to a Django model instance.
5
+ Home-page: https://github.com/nibblex/django-field-logger
6
+ Author: Sergio Rodríguez
7
+ Author-email: srodriguez3441@gmail.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ License-File: LICENSE
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ setup.py
5
+ django_field_logger.egg-info/PKG-INFO
6
+ django_field_logger.egg-info/SOURCES.txt
7
+ django_field_logger.egg-info/dependency_links.txt
8
+ django_field_logger.egg-info/requires.txt
9
+ django_field_logger.egg-info/top_level.txt
10
+ fieldlogger/__init__.py
11
+ fieldlogger/apps.py
12
+ fieldlogger/config.py
13
+ fieldlogger/fieldlogger.py
14
+ fieldlogger/models.py
15
+ fieldlogger/signals.py
File without changes
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class FieldloggerConfig(AppConfig):
5
+ default_auto_field = "django.db.models.BigAutoField"
6
+ name = "fieldlogger"
@@ -0,0 +1,99 @@
1
+ from datetime import date, datetime, time, timedelta
2
+ from decimal import Decimal
3
+ from json import JSONEncoder, JSONDecoder
4
+
5
+ from django.conf import settings
6
+ from django.db import models
7
+ from django.utils.module_loading import import_string
8
+
9
+
10
+ SETTINGS = getattr(settings, "FIELD_LOGGER_SETTINGS", {})
11
+
12
+
13
+ class Encoder(JSONEncoder):
14
+ def default(self, obj):
15
+ if isinstance(obj, (date, datetime, time)):
16
+ return obj.isoformat()
17
+
18
+ if isinstance(obj, timedelta):
19
+ return obj.total_seconds()
20
+
21
+ if isinstance(obj, Decimal):
22
+ return str(obj)
23
+
24
+ if isinstance(obj, (bytes, bytearray)):
25
+ return obj.decode()
26
+
27
+ if isinstance(obj, memoryview):
28
+ return obj.tobytes().decode()
29
+
30
+ if isinstance(obj, models.Model):
31
+ return obj.pk
32
+
33
+ if isinstance(obj, models.QuerySet):
34
+ return list(obj.values_list("pk", flat=True))
35
+
36
+ return super().default(obj)
37
+
38
+
39
+ class Decoder(JSONDecoder):
40
+ pass
41
+
42
+
43
+ def logging_enabled(*configs):
44
+ return SETTINGS.get("LOGGING_ENABLED", True) and all(
45
+ config.get("logging_enabled", True) for config in configs
46
+ )
47
+
48
+
49
+ def logging_fields(instance):
50
+ model_config = LOGGING_CONFIG.get(instance._meta.label, {})
51
+ logging_fields = model_config.get("fields", [])
52
+ if not logging_fields:
53
+ exclude_fields = model_config.get("exclude_fields", [])
54
+ logging_fields = [
55
+ field.name
56
+ for field in instance._meta.fields
57
+ if field.name not in exclude_fields
58
+ ]
59
+
60
+ return frozenset(logging_fields)
61
+
62
+
63
+ def callbacks(*configs):
64
+ callbacks = SETTINGS.get("CALLBACKS", [])
65
+ for config in configs:
66
+ callbacks += config.get("callbacks", [])
67
+
68
+ callbacks = map(
69
+ lambda callback: import_string(callback)
70
+ if isinstance(callback, str)
71
+ else callback,
72
+ callbacks,
73
+ )
74
+
75
+ return list(callbacks)
76
+
77
+
78
+ ENCODER = SETTINGS.get("ENCODER")
79
+ ENCODER = import_string(ENCODER) if ENCODER else Encoder
80
+
81
+ DECODER = SETTINGS.get("DECODER")
82
+ DECODER = import_string(DECODER) if DECODER else Decoder
83
+
84
+ LOGGING_APPS = SETTINGS.get("LOGGING_APPS", {})
85
+
86
+ LOGGING_CONFIG = {}
87
+ for app, app_config in LOGGING_APPS.items():
88
+ if not app_config or not logging_enabled(SETTINGS, app_config):
89
+ continue
90
+
91
+ for model, model_config in app_config.get("models", {}).items():
92
+ if not model_config or not logging_enabled(SETTINGS, app_config, model_config):
93
+ continue
94
+
95
+ model_config.update(
96
+ {"callbacks": callbacks(SETTINGS, app_config, model_config)}
97
+ )
98
+
99
+ LOGGING_CONFIG[f"{app}.{model}"] = model_config
@@ -0,0 +1,53 @@
1
+ from django.core.exceptions import FieldDoesNotExist
2
+
3
+ # Helpers
4
+
5
+
6
+ def rgetattr(obj, attr, *args):
7
+ from functools import reduce
8
+
9
+ def _getattr(obj, attr):
10
+ return getattr(obj, attr, *args)
11
+
12
+ return reduce(_getattr, [obj] + attr.split("."))
13
+
14
+
15
+ def rsetattr(obj, attr, val, save=False):
16
+ pre, _, post = attr.rpartition(".")
17
+ obj_to_save = rgetattr(obj, pre) if pre else obj
18
+ setattr(obj_to_save, post, val)
19
+ if save:
20
+ obj_to_save.save(update_fields=[post])
21
+
22
+
23
+ # Main function
24
+
25
+
26
+ def log_fields(instance, fields):
27
+ logs = {}
28
+
29
+ pre_instance = instance.__class__.objects.get(pk=instance.pk)
30
+
31
+ for field in fields:
32
+ try:
33
+ field_model = instance._meta.get_field(field)
34
+ new_value = field_model.to_python(rgetattr(instance, field))
35
+ old_value = rgetattr(pre_instance, field)
36
+ except (FieldDoesNotExist, AttributeError):
37
+ continue
38
+
39
+ if new_value == old_value:
40
+ continue
41
+
42
+ logs[field] = instance.field_logs.create(
43
+ app_label=instance._meta.app_label,
44
+ model=instance._meta.model_name,
45
+ object_id=instance.pk,
46
+ field=field,
47
+ old_value=old_value,
48
+ new_value=new_value,
49
+ )
50
+
51
+ rsetattr(instance, field, new_value)
52
+
53
+ return logs
@@ -0,0 +1,57 @@
1
+ from django.apps import apps
2
+ from django.db import models
3
+ from django.utils.translation import gettext_lazy as _
4
+
5
+ from .config import ENCODER, DECODER
6
+
7
+
8
+ class FieldLog(models.Model):
9
+ app_label = models.CharField(max_length=100, editable=False)
10
+ model = models.CharField(_("model class name"), max_length=100, editable=False)
11
+ object_id = models.PositiveIntegerField(editable=False)
12
+ field = models.CharField(_("field name"), max_length=100, editable=False)
13
+ old_value = models.JSONField(
14
+ encoder=ENCODER, decoder=DECODER, blank=True, null=True, editable=False
15
+ )
16
+ timestamp = models.DateTimeField(auto_now=True, editable=False)
17
+ new_value = models.JSONField(
18
+ encoder=ENCODER, decoder=DECODER, blank=True, null=True, editable=False
19
+ )
20
+ extra_data = models.JSONField(default=dict)
21
+
22
+ def __str__(self):
23
+ return f"({self.field}) {self.old_value} -> {self.new_value}"
24
+
25
+ @classmethod
26
+ def from_db(cls, db, field_names, values):
27
+ field_class = apps.get_model(values[1], values[2])._meta.get_field(values[4])
28
+ instance = super().from_db(db, field_names, values)
29
+ instance.old_value = field_class.to_python(instance.old_value)
30
+ instance.new_value = field_class.to_python(instance.new_value)
31
+ return instance
32
+
33
+ @property
34
+ def model_class(self):
35
+ return apps.get_model(self.app_label, self.model)
36
+
37
+ @property
38
+ def instance(self):
39
+ return self.model_class.objects.get(pk=self.object_id)
40
+
41
+ @property
42
+ def previous_log(self):
43
+ return (
44
+ self.__class__.objects.filter(
45
+ app_label=self.app_label,
46
+ model=self.model,
47
+ object_id=self.object_id,
48
+ field=self.field,
49
+ )
50
+ .exclude(pk=self.pk)
51
+ .order_by("-pk")
52
+ .last()
53
+ )
54
+
55
+ @property
56
+ def created(self):
57
+ return not self.previous_log
@@ -0,0 +1,26 @@
1
+ from django.db.models.signals import pre_save
2
+
3
+ from .config import LOGGING_CONFIG, logging_fields
4
+ from .fieldlogger import log_fields
5
+
6
+
7
+ def log_dirty_fields(sender, instance, *args, **kwargs):
8
+ if instance.pk:
9
+ using_fields = logging_fields(instance)
10
+
11
+ update_fields = kwargs["update_fields"] or frozenset()
12
+ if update_fields:
13
+ using_fields = using_fields & update_fields
14
+
15
+ if using_fields:
16
+ logs = log_fields(instance, using_fields)
17
+ if logs and "timestamps" not in update_fields:
18
+ kwargs["update_fields"] = update_fields | frozenset(["timestamps"])
19
+
20
+ callbacks = LOGGING_CONFIG[sender._meta.label].get("callbacks", [])
21
+ for callback in callbacks:
22
+ callback(instance, using_fields, logs)
23
+
24
+
25
+ for label in LOGGING_CONFIG:
26
+ pre_save.connect(log_dirty_fields, label)
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,24 @@
1
+ import os
2
+ import setuptools
3
+
4
+ # allow setup.py to be run from any path
5
+ os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
6
+
7
+ setuptools.setup(
8
+ name="django-field-logger",
9
+ version="0.0.1",
10
+ author="Sergio Rodríguez",
11
+ author_email="srodriguez3441@gmail.com",
12
+ description="""A python package which logs each change made to a Django model instance.""",
13
+ url="https://github.com/nibblex/django-field-logger",
14
+ packages=setuptools.find_packages(),
15
+ license="MIT",
16
+ classifiers=[
17
+ "Programming Language :: Python :: 3",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ ],
21
+ install_requires=[
22
+ "Django>=1.11",
23
+ ],
24
+ )