I want to make my UUID's prettier so I've gone about implementing a
ShortUUID column based on the shortuuid library[1]. The idea is to store
the primary key as a UUID type in postgres (since its optimized for that)
and transform the UUID to a shortuuid for presentation and querying. This
is my first attempt at implementing it. It has some short comings.
I was wondering if you had any advice for fully baking the implementation.
I've pasted the code I have so far.
from sqlalchemy_utils.types.uuid import UUIDType
import uuid
import shortuuid
def _decode_shortuuid(value):
try:
return shortuuid.decode(value)
except ValueError:
return None
def _encode_shortuuid(value):
try:
if value is None:
return None
return shortuuid.encode(value)
except KeyError:
return None
class ShortUUID(UUIDType):
"""Converts UUIDs to ShortUUIDs for readability's sake."""
def process_bind_param(self, value, dialect):
"""Process a ShortUUID to a UUID."""
if value is None:
return value
if type(value) != uuid.UUID:
value = _decode_shortuuid(value)
return super().process_bind_param(value, dialect)
def process_result_value(self, value, dialect):
"""Return a ShortUUID encoded UUID."""
value = super().process_result_value(value, dialect)
return _encode_shortuuid(value)
1. https://github.com/skorokithakis/shortuuid
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
http://www.sqlalchemy.org/
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable
Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.