Passed
Push — master ( 5a4f44...92a53b )
by Swen
01:57
created

LocalizedUniqueSlugField   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 92
Duplicated Lines 0 %

Test Coverage

Coverage 97.14%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 92
ccs 34
cts 35
cp 0.9714
rs 10
wmc 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 12 1
D pre_save() 0 53 10
A deconstruct() 0 10 1
1 1
from datetime import datetime
2
3 1
from django.utils.text import slugify
0 ignored issues
show
Configuration introduced by
The import django.utils.text could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
4 1
from django.core.exceptions import ImproperlyConfigured
0 ignored issues
show
Configuration introduced by
The import django.core.exceptions could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
5
6 1
from .autoslug_field import LocalizedAutoSlugField
7 1
from ..util import get_language_codes
8 1
from ..mixins import AtomicSlugRetryMixin
9 1
from ..value import LocalizedValue
10
11
12 1
class LocalizedUniqueSlugField(LocalizedAutoSlugField):
13
    """Automatically provides slugs for a localized
14
    field upon saving."
15
16
    An improved version of :see:LocalizedAutoSlugField,
17
    which adds:
18
19
        - Concurrency safety
20
        - Improved performance
21
22
    When in doubt, use this over :see:LocalizedAutoSlugField.
23
    Inherit from :see:AtomicSlugRetryMixin in your model to
24
    make this field work properly.
25
    """
26
27 1
    def __init__(self, *args, **kwargs):
28
        """Initializes a new instance of :see:LocalizedUniqueSlugField."""
29
30 1
        kwargs['uniqueness'] = kwargs.pop('uniqueness', get_language_codes())
31
32 1
        super(LocalizedUniqueSlugField, self).__init__(
33
            *args,
34
            **kwargs
35
        )
36
37 1
        self.populate_from = kwargs.pop('populate_from')
38 1
        self.include_time = kwargs.pop('include_time', False)
39
40 1
    def deconstruct(self):
41
        """Deconstructs the field into something the database
42
        can store."""
43
44 1
        name, path, args, kwargs = super(
45
            LocalizedUniqueSlugField, self).deconstruct()
46
47 1
        kwargs['populate_from'] = self.populate_from
48 1
        kwargs['include_time'] = self.include_time
49 1
        return name, path, args, kwargs
50
51 1
    def pre_save(self, instance, add: bool):
52
        """Ran just before the model is saved, allows us to built
53
        the slug.
54
55
        Arguments:
56
            instance:
57
                The model that is being saved.
58
59
            add:
60
                Indicates whether this is a new entry
61
                to the database or an update.
62
63
        Returns:
64
            The localized slug that was generated.
65
        """
66
67 1
        if not isinstance(instance, AtomicSlugRetryMixin):
68
            raise ImproperlyConfigured((
69
                'Model \'%s\' does not inherit from AtomicSlugRetryMixin. '
70
                'Without this, the LocalizedUniqueSlugField will not work.'
71
            ) % type(instance).__name__)
72
73 1
        slugs = LocalizedValue()
74
75 1
        for lang_code, value in self._get_populate_values(instance):
76 1
            if not value:
77 1
                continue
78
79 1
            slug = slugify(value, allow_unicode=True)
80
81
            # verify whether it's needed to re-generate a slug,
82
            # if not, re-use the same slug
83 1
            if instance.pk is not None:
84 1
                current_slug = getattr(instance, self.name).get(lang_code)
0 ignored issues
show
Bug introduced by
The Instance of LocalizedUniqueSlugField does not seem to have a member named name.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
85 1
                if current_slug is not None:
86 1
                    stripped_slug = current_slug[0:current_slug.rfind('-')]
87 1
                    if slug == stripped_slug:
88 1
                        slugs.set(lang_code, current_slug)
89 1
                        continue
90
91 1
            if self.include_time:
92 1
                slug += '-%d' % datetime.now().microsecond
93
94 1
            if instance.retries > 0:
95
                # do not add another - if we already added time
96 1
                if not self.include_time:
97 1
                    slug += '-'
98 1
                slug += '%d' % instance.retries
99
100 1
            slugs.set(lang_code, slug)
101
102 1
        setattr(instance, self.name, slugs)
0 ignored issues
show
Bug introduced by
The Instance of LocalizedUniqueSlugField does not seem to have a member named name.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
103
        return slugs
104