Generate slug in app

This commit is contained in:
Charlotte Van Petegem 2022-05-30 19:48:23 +02:00
parent 4a353ec17e
commit 01b5c72e7b
No known key found for this signature in database
GPG key ID: 019E764B7184435A
2 changed files with 8 additions and 18 deletions

View file

@ -24,22 +24,7 @@ def upgrade():
))
op.create_unique_constraint('order_slug_unique', 'order', ['slug'])
# Trigger to handle duplicates: generate new slug if slug already exists
op.execute(text(
"""
CREATE TRIGGER order_before_insert
BEFORE UPDATE ON `order`
FOR EACH ROW
BEGIN
WHILE (NEW.slug IS NULL OR (SELECT id FROM `order` WHERE slug = NEW.slug) IS NOT NULL) DO
SET NEW.slug = SUBSTRING(MD5(RAND()) FROM 1 FOR 7);
END WHILE;
END
"""
))
def downgrade():
op.execute(text("DROP TRIGGER order_before_insert"))
op.drop_constraint('order_slug_unique', 'order', type_='unique')
op.drop_column('order', 'slug')

View file

@ -2,6 +2,7 @@
import typing
from collections import defaultdict
from datetime import datetime
import secrets
import string
from hlds.definitions import location_definitions
@ -10,6 +11,12 @@ from utils import first
from .database import db
from .user import User
def generate_slug():
alphabet = string.ascii_letters + string.digits
secret = ''.join(secrets.choice(alphabet) for i in range(7))
while Order.query.filter(Order.slug == secret).first() is not None:
secret = ''.join(secrets.choice(alphabet) for i in range(7))
return secret
class Order(db.Model):
"""Class used for configuring the Order model in the database"""
@ -20,9 +27,7 @@ class Order(db.Model):
starttime = db.Column(db.DateTime)
stoptime = db.Column(db.DateTime)
public = db.Column(db.Boolean, default=True)
# The default value for `slug`, a random 7-character alphanumerical string,
# is created on the database side. See migrations/versions/29ccbe077c57_add_slug.py
slug = db.Column(db.String(7), unique=True)
slug = db.Column(db.String(7), default=generate_slug, unique=True)
association = db.Column(db.String(120), nullable=False, server_default="")
items = db.relationship("OrderItem", backref="order", lazy="dynamic")