The personal URL shortener
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.8 KiB

import uuid
import typing
import logging
from cloudant.document import Document
class Shortener:
Shortener object
def __init__(self, pointer_db, configuration: dict) -> typing.NoReturn:
Initialize the Shortener object.
:param pointer_db: The Pointer Database object.
:param configuration: The shortenit configuration.
self.logger = logging.getLogger(self.__class__.__name__)
self.pointer_db = pointer_db
self.uuid = None
self.length = 32
self.check_duplicate = False
self.upper_case = False
self.configuration = configuration
def init(self) -> typing.NoReturn:
Initialize the shortener from the configuration.
length = self.configuration.get("id_length", 32)
if length >= 32 or length <= 0:
self.length = 32
self.length = length
self.check_duplicate = self.configuration.get(
"check_duplicate_id", False)
self.upper_case = self.configuration.get(
"id_upper_case", False)
def generate_short_uuid(self) -> str:
Generate a short UUID in Hex format.
:returns: A short UUID in Hex format.
short_uuid = uuid.uuid1().hex
if self.upper_case:
return short_uuid.upper()[0:self.length]
return short_uuid.lower()[0:self.length]
def check_uuid(self, short_uuid) -> bool:
Check a short UUID against the database.
:returns: Whether the UUID exists in the database or not.
with Document(self.pointer_db, 'pointer') as pointer:
self.logger.debug("Pointer: %s", pointer)
self.uuid = pointer[short_uuid]
except KeyError:"Generated short uuid '%s'"
"was not found in database",
return False
return True
def get_id(self) -> str:
Method to get a UUID.
This method will generate a UUID and checks if it already exists in the database.
:returns: A UUID.
short_uuid = self.generate_short_uuid()
if self.check_duplicate:
counter = 0
while self.check_uuid(short_uuid):
if counter > 10:
self.logger.err("Cannot generate new unique ID,"
"try to configure a longer ID length.")
return None
short_uuid = self.generate_short_uuid()
counter += 1
self.logger.debug("Returning ID: '%s'", short_uuid)
return short_uuid