From d1543396579b064e33391286b1e18ea18691b28b Mon Sep 17 00:00:00 2001 From: Julien Palard Date: Fri, 21 Apr 2023 10:31:46 +0200 Subject: [PATCH] Simplier uuid picker --- paste/models.py | 10 ++++++++++ paste/tools.py | 24 ------------------------ paste/views.py | 5 +++-- 3 files changed, 13 insertions(+), 26 deletions(-) delete mode 100644 paste/tools.py diff --git a/paste/models.py b/paste/models.py index 788e5e8..77b547e 100644 --- a/paste/models.py +++ b/paste/models.py @@ -4,6 +4,7 @@ from django.utils import timezone from datetime import datetime, timedelta from webtools import settings from django.utils.translation import gettext_lazy as _ +import shortuuid EXPIRE_CHOICES = ( @@ -70,3 +71,12 @@ class Paste(models.Model): def __str__(self): excerpt = repr(self.content[:100]) + ("..." if len(self.content) > 100 else "") return f"{self.slug} - {excerpt}" + + def choose_slug(self): + while True: + uuid = shortuuid.uuid() + for i in range(4, len(uuid)): + potential_uuid = uuid[:i] + if not type(self).objects.filter(slug=potential_uuid): + self.slug = potential_uuid + return diff --git a/paste/tools.py b/paste/tools.py deleted file mode 100644 index fb0505e..0000000 --- a/paste/tools.py +++ /dev/null @@ -1,24 +0,0 @@ -from string import digits, ascii_uppercase -from random import choice, choices -import shortuuid -import os -from webtools import settings - - -def random_id(model): - """Returns a short uuid for the slug of the given model. - - If a DICT is given in the settings, try to use it to generate - nicer URLS like: - """ - pool = digits + ascii_uppercase - slug = choice(digits) + choice(ascii_uppercase) + "-" + "".join(choices(pool, k=2)) - if not model.objects.filter(slug=slug): - return slug - # fallback to the shortuuid strategy: - uuid = choice("0123456789") + shortuuid.uuid() - for i in range(3, len(uuid)): - potential_uuid = uuid[:i] - if not model.objects.filter(slug=potential_uuid): - return potential_uuid - return uuid diff --git a/paste/views.py b/paste/views.py index 41c54f6..1c16334 100644 --- a/paste/views.py +++ b/paste/views.py @@ -5,7 +5,7 @@ from django.http import HttpResponseRedirect, HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Paste, Language from .forms import PasteForm -from .tools import random_id + from webtools import settings @@ -14,7 +14,8 @@ def index(request): """Displays form.""" data = {"menu": "index", "max_characters": settings.PASTE["max_characters"]} if request.method == "POST": - paste = Paste(slug=random_id(Paste)) + paste = Paste() + paste.choose_slug() if request.FILES: for language_name, any_file in request.FILES.items(): break