Passed
Push — master ( 5db877...bb1125 )
by Swen
01:45
created

AtomicSlugRetryMixin.save()   B

Complexity

Conditions 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.0131

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
dl 0
loc 29
ccs 13
cts 14
cp 0.9286
crap 6.0131
rs 7.5384
1 1
from django.db import transaction
2 1
from django.conf import settings
3 1
from django.db.utils import IntegrityError
4
5
6 1
class AtomicSlugRetryMixin:
7
    """Makes :see:LocalizedUniqueSlugField work by retrying upon
8
    violation of the UNIQUE constraint."""
9
10 1
    def save(self, *args, **kwargs):
11
        """Saves this model instance to the database."""
12
13 1
        max_retries = getattr(
14
            settings,
15
            'LOCALIZED_FIELDS_MAX_RETRIES',
16
            100
17
        )
18
19 1
        if not hasattr(self, 'retries'):
20 1
            self.retries = 0
21
22 1
        with transaction.atomic():
23 1
            try:
24 1
                return super().save(*args, **kwargs)
25 1
            except IntegrityError as ex:
26
                # this is as retarded as it looks, there's no
27
                # way we can put the retry logic inside the slug
28
                # field class... we can also not only catch exceptions
29
                # that apply to slug fields... so yea.. this is as
30
                # retarded as it gets... i am sorry :(
31 1
                if 'slug' not in str(ex):
32
                    raise ex
33
34 1
                if self.retries >= max_retries:
35 1
                    raise ex
36
37 1
        self.retries += 1
38
        return self.save()
39