pasteque/paste/tools.py

25 lines
773 B
Python
Raw Normal View History

from string import digits, ascii_uppercase
from random import choice, choices
2013-04-04 17:37:30 +00:00
import shortuuid
import os
from webtools import settings
2020-05-31 15:50:04 +00:00
2018-05-06 22:35:52 +00:00
def random_id(model):
2020-05-31 15:50:04 +00:00
"""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:
2020-05-31 15:50:04 +00:00
"""
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()
2018-05-06 22:35:52 +00:00
for i in range(3, len(uuid)):
2018-05-12 21:23:57 +00:00
potential_uuid = uuid[:i]
if not model.objects.filter(slug=potential_uuid):
return potential_uuid
2018-05-06 22:35:52 +00:00
return uuid