pasteque/paste/tools.py

71 lines
1.8 KiB
Python
Raw Normal View History

2013-04-04 17:37:30 +00:00
import string
2018-05-12 21:23:57 +00:00
import random
2013-04-04 17:37:30 +00:00
import shortuuid
import os
2020-05-31 15:50:04 +00:00
import re
2013-04-04 17:37:30 +00:00
from webtools import settings
2020-05-31 15:50:04 +00:00
from functools import lru_cache
2018-05-06 22:35:52 +00:00
from .models import Paste
2018-05-12 21:23:57 +00:00
2020-05-31 15:50:04 +00:00
@lru_cache()
def find_words():
if not settings.DICT:
return None
short_words = []
try:
with open(settings.DICT) as dictionary:
for line in dictionary:
line = line.strip()
if re.match("[a-z]{2,5}$", line):
short_words.append(line)
return short_words
except FileNotFoundError:
return None
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:
"""
short_words = find_words()
if short_words:
slug = (
random.choice(string.digits)
+ random.choice(string.ascii_uppercase)
+ "-"
+ random.choice(short_words)
)
if not model.objects.filter(slug=slug):
return slug
# else, fallback to the shortuuid strategy:
2020-05-31 13:33:59 +00:00
uuid = random.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
2013-04-04 17:37:30 +00:00
def cache_get_filepath(key):
"""Returns cache path."""
return os.path.join(settings.CACHE_PATH, key)
def cache_exists(key):
"""Says if cache exists for key."""
return os.path.isfile(cache_get_filepath(key))
def cache_store(key, value):
"""Store cache value for key."""
2020-05-31 13:33:59 +00:00
with open(cache_get_filepath(key), "w") as cache_file:
2018-05-06 21:19:49 +00:00
cache_file.write(value)
2013-04-04 17:37:30 +00:00
def cache_fetch(key):
"""Fetch cache value for key."""
2020-05-31 13:33:59 +00:00
with open(cache_get_filepath(key), "r") as cache_file:
2013-04-04 17:37:30 +00:00
return cache_file.read()