Simplier uuid picker
This commit is contained in:
parent
459d80eab7
commit
d154339657
|
@ -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
|
||||
|
|
|
@ -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
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue