Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix transliteration and add types #84

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion autoslug/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ class AbstractModelWithCustomManager(Model):
class Meta:
abstract = True

def delete(self, using=None):
def delete(self, **kwargs):
self.is_deleted = True
self.save()

Expand Down
38 changes: 29 additions & 9 deletions autoslug/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

# Copyright (c) 2018-present Justin Mayer
# Copyright (c) 2008—2016 Andy Mikhailenko
#
Expand All @@ -7,15 +9,28 @@
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README for copying conditions.
#
import datetime
from typing import TYPE_CHECKING, Any, Tuple

# django
import datetime
from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist
from django.core.exceptions import FieldDoesNotExist
from django.db.models import ForeignKey
from django.db.models.fields import DateField
from django.template.defaultfilters import slugify as django_slugify
from django.utils.timezone import localtime, is_aware


if TYPE_CHECKING: # pragma: no cover
from collections.abc import Callable, Generator, Sequence
from django.db.models import SlugField, Model, Manager
from django.db.models.base import Options
from .fields import AutoSlugField

SlugifyFunction = Callable[[str], str]
# This is enough to satisfy how it is used.
class DjangoModel(Model):
_meta: Options = ...

try:
# i18n-friendly approach
from unidecode import unidecode
Expand All @@ -32,7 +47,7 @@ def slugify(value):
return django_slugify(unidecode(value))


def get_prepopulated_value(field, instance):
def get_prepopulated_value(field: AutoSlugField, instance: DjangoModel) -> Any:
"""
Returns preliminary value based on `populate_from`.
"""
Expand All @@ -45,7 +60,7 @@ def get_prepopulated_value(field, instance):
return callable(attr) and attr() or attr


def generate_unique_slug(field, instance, slug, manager):
def generate_unique_slug(field: AutoSlugField, instance: DjangoModel, slug: str, manager: Manager):
"""
Generates unique slug by adding a number to given value until no model
instance can be found with such slug. If ``unique_with`` (a tuple of field
Expand Down Expand Up @@ -91,7 +106,7 @@ def generate_unique_slug(field, instance, slug, manager):
# ...next iteration...


def get_uniqueness_lookups(field, instance, unique_with):
def get_uniqueness_lookups(field: AutoSlugField, instance: DjangoModel, unique_with: Sequence[str]) -> Generator[Tuple[str, str], None, None]:
"""
Returns a dict'able tuple of lookups to ensure uniqueness of a slug.
"""
Expand Down Expand Up @@ -164,7 +179,7 @@ def get_uniqueness_lookups(field, instance, unique_with):
yield field_name, value


def crop_slug(field, slug):
def crop_slug(field: SlugField, slug: str):
if field.max_length < len(slug):
return slug[:field.max_length]
return slug
Expand All @@ -178,23 +193,28 @@ def crop_slug(field, slug):
import re
PUNCT_RE = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')

def translitcodec_slugify(codec):
def _slugify(value, delim='-', encoding=''):
def translitcodec_slugify(codec) -> SlugifyFunction:
# TODO: delim and encoding probably belong on the wrapper
def _slugify(value: str, delim: str ='-', encoding: str=''):
"""
Generates an ASCII-only slug.
This works because translitcodec registers itself with python's
codecs registry, so there's no translitcodec module called here
directly, but via str.encode().

Borrowed from http://flask.pocoo.org/snippets/5/
"""
if encoding:
encoder = f"{codec}/{encoding}"
else:
encoder = codec
_delim = delim.encode(encoder)
result = []
for word in PUNCT_RE.split(value.lower()):
word = word.encode(encoder)
if word:
result.append(word)
return unicode(delim.join(result))
return str(_delim.join(result))
return _slugify

translit_long = translitcodec_slugify("translit/long")
Expand Down
2 changes: 1 addition & 1 deletion requirements/devel.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
coverage==5.0.3
coverage==7.3.2
1 change: 1 addition & 0 deletions run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
),
),
AUTOSLUG_SLUGIFY_FUNCTION = 'django.template.defaultfilters.slugify',
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
)


Expand Down