From b939ad415df847624cca18ce7cd32fd9456fa14a Mon Sep 17 00:00:00 2001 From: Scott Wallace Date: Mon, 16 May 2022 10:45:39 +0100 Subject: [PATCH] Add ability to add new entry with custom shortcode --- slinky/__init__.py | 12 +++++-- slinky/templates/add.html | 7 ++-- slinky/web.py | 67 ++++++++++++++++++++++++++++++--------- templates/error.html | 7 ++++ tests/test_slinky.py | 17 ++++++++-- tests/test_web.py | 67 +++++++++++++++++++++++---------------- 6 files changed, 127 insertions(+), 50 deletions(-) create mode 100644 templates/error.html diff --git a/slinky/__init__.py b/slinky/__init__.py index a4c6764..05f18eb 100644 --- a/slinky/__init__.py +++ b/slinky/__init__.py @@ -50,9 +50,10 @@ class Slinky: self.db = db.ShortcodeDB(db_url) # pylint: disable=invalid-name self.session = self.db.session() - def add( + def add( # pylint: disable=too-many-arguments self, - url: str, + shortcode: str = '', + url: str = '', length: int = 4, fixed_views: int = -1, expiry: datetime = datetime.max, @@ -61,7 +62,11 @@ class Slinky: Add a shortcode to the DB Args: + shortcode (str): URL path to use for the shortcode. If not provided, + one will be generated. url (str): URL to redirect to + length (int): length of the desired shortcode. Only used when a shortcode + is generated. Defaults to 4. fixed_views (int, optional): number of views to serve before expiring. Defaults to 0 (no limit). expiry (int, optional): date of expiry. Defaults to 0 (no limit). @@ -69,7 +74,8 @@ class Slinky: Returns: str: shortcode for the redirect """ - shortcode = random_string(length=length) + if not shortcode: + shortcode = random_string(length=length) if self.get_by_shortcode(shortcode).url: raise ValueError(f'Shortcode {shortcode} already exists') diff --git a/slinky/templates/add.html b/slinky/templates/add.html index 4851bae..638a67d 100644 --- a/slinky/templates/add.html +++ b/slinky/templates/add.html @@ -7,10 +7,11 @@
+ {{ form.shortcode.label }} {{ form.shortcode(value=shortcode) }}
{{ form.url.label }} {{ form.url }}
{{ form.length.label }} {{ form.length }}
{{ form.fixed_views.label }} {{ form.fixed_views }} (-1 for unlimited)
- {{ form.expiry.label}} {{ form.expiry(class='datepicker') }} (leave as default for unlimited)
+ {{ form.expiry.label}} {{ form.expiry(class="datepicker") }} (leave as default for unlimited)