• Stars
    star
    1,905
  • Rank 23,361 (Top 0.5 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 13 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A generator library for concise, unambiguous and URL-safe UUIDs.

Description

shortuuid is a simple python library that generates concise, unambiguous, URL-safe UUIDs.

Often, one needs to use non-sequential IDs in places where users will see them, but the IDs must be as concise and easy to use as possible. shortuuid solves this problem by generating uuids using Python's built-in uuid module and then translating them to base57 using lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.

image

Installation

To install shortuuid you need:

  • Python 3.6+

If you have the dependencies, you have multiple options of installation:

Usage

To use shortuuid, just import it in your project like so:

>>> import shortuuid

You can then generate a short UUID:

>>> shortuuid.uuid()
'vytxeTZskVKR7C7WgdSP3d'

If you prefer a version 5 UUID, you can pass a name (DNS or URL) to the call and it will be used as a namespace (uuid.NAMESPACE_DNS or uuid.NAMESPACE_URL) for the resulting UUID:

>>> shortuuid.uuid(name="example.com")
'exu3DTbj2ncsn9tLdLWspw'

>>> shortuuid.uuid(name="<http://example.com>")
'shortuuid.uuid(name="<http://example.com>")'

You can also generate a cryptographically secure random string (using os.urandom() internally) with:

>>> shortuuid.ShortUUID().random(length=22)
'RaF56o2r58hTKT7AYS9doj'

To see the alphabet that is being used to generate new UUIDs:

>>> shortuuid.get_alphabet()
'23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

If you want to use your own alphabet to generate UUIDs, use set_alphabet():

>>> shortuuid.set_alphabet("aaaaabcdefgh1230123")
>>> shortuuid.uuid()
'0agee20aa1hehebcagddhedddc0d2chhab3b'

The default alphabet matches the regex [2-9A-HJ-NP-Za-km-z]{22}.

shortuuid will automatically sort and remove duplicates from your alphabet to ensure consistency:

>>> shortuuid.get_alphabet()
'0123abcdefgh'

If the default 22 digits are too long for you, you can get shorter IDs by just truncating the string to the desired length. The IDs won't be universally unique any longer, but the probability of a collision will still be very low.

To serialize existing UUIDs, use encode() and decode():

>>> import uuid
>>> u = uuid.uuid4()
>>> u
UUID('6ca4f0f8-2508-4bac-b8f1-5d1e3da2247a')

>>> s = shortuuid.encode(u)
>>> s
'MLpZDiEXM4VsUryR9oE8uc'

>>> shortuuid.decode(s) == u
True

>>> short = s[:7]
>>> short
'MLpZDiE'

>>> h = shortuuid.decode(short)
UUID('00000000-0000-0000-0000-009a5b27f8b9')

>>> shortuuid.decode(shortuuid.encode(h)) == h
True

Class-based usage

If you need to have various alphabets per-thread, you can use the ShortUUID class, like so:

>>> su = shortuuid.ShortUUID(alphabet="01345678")
>>> su.uuid()
'034636353306816784480643806546503818874456'

>>> su.get_alphabet()
'01345678'

>>> su.set_alphabet("21345687654123456")
>>> su.get_alphabet()
'12345678'

Command-line usage

shortuuid provides a simple way to generate a short UUID in a terminal:

$ shortuuid
fZpeF6gcskHbSpTgpQCkcJ

Django field

shortuuid includes a Django field that generates random short UUIDs by default, for your convenience:

from shortuuid.django_fields import ShortUUIDField

class MyModel(models.Model):
    # A primary key ID of length 16 and a short alphabet.
    id = ShortUUIDField(
        length=16,
        max_length=40,
        prefix="id_",
        alphabet="abcdefg1234",
        primary_key=True,
    )

    # A short UUID of length 22 and the default alphabet.
    api_key = ShortUUIDField()

The field is the same as the CharField, with a length argument (the length of the ID), an alphabet argument, and the default argument removed. Everything else is exactly the same, e.g. index, help_text, max_length, etc.

Compatibility note

Versions of ShortUUID prior to 1.0.0 generated UUIDs with their MSB last, i.e. reversed. This was later fixed, but if you have some UUIDs stored as a string with the old method, you need to pass legacy=True to decode() when converting your strings back to UUIDs.

That option will go away in the future, so you will want to convert your UUIDs to strings using the new method. This can be done like so:

>>> new_uuid_str = encode(decode(old_uuid_str, legacy=True))

License

shortuuid is distributed under the BSD license.

More Repositories

1

catt

Cast All The Things allows you to send videos from many, many online sources to your Chromecast.
Python
3,257
star
2

django-annoying

A django application that tries to eliminate annoying things in the Django framework. ⛺
Python
917
star
3

expounder

A library for explaining things in HTML.
JavaScript
482
star
4

tbvaccine

A small utility to pretty-print Python tracebacks. ⛺
Python
376
star
5

django-loginas

"Log in as user" for the Django admin.
Python
355
star
6

python-yeelight

A Python library for controlling YeeLight WiFi RGB bulbs (mirror of https://gitlab.com/stavros/python-yeelight).
Python
262
star
7

goatfish

A small, schemaless Python ORM that is backed by SQLite. ⛺
Python
233
star
8

netproxy

A Netflix/Hulu/Pandora/etc proxy in a box.
Python
230
star
9

python-fuse-sample

A sample FUSE filesystem in Python.
Python
169
star
10

django-project-template

The Django project template I use, for installation with django-admin.
Python
161
star
11

gr8w8upd8m8

Gr8W8Upd8M8 is a script to automatically read your weight from a Wii Balance Board. ⛺
Python
145
star
12

imdbapi

An API for the IMDB site. ⛺
Python
131
star
13

A6lib

An ESP8266/Arduino library for communicating with the A6 GSM module. ⛺
C++
127
star
14

jsane

A saner way to traverse JSON in Python
Python
125
star
15

encbup

Encrypted backups (without the backups)
Python
121
star
16

sysaidmin

A GPT-powered sysadmin.
Python
115
star
17

tiny-ESP8266-breakout

A very small and basic ESP8266 breakout board
110
star
18

omnisync

omnisync is a universal file synchroniser and backup program (think rsync) that supports multiple transport systems (such as plain files, sftp, s3 and virtual, currently, and support for ftp, http, et al is planned). It is designed to be fast, small, extensible, portable and bandwidth-efficient. It is available for Linux, Windows and Mac. ⛺
Python
87
star
19

iRotary

One man's quest to turn an old rotary phone into a mobile phone.
Arduino
83
star
20

django-cloudflare-push

A piece of middleware that uses Cloudflare's HTTP/2 Push to push static media to the clients. ⛺
Python
75
star
21

gweet

A message queue for the abhorrently named Internet of Things
Go
70
star
22

static-appengine-hoster

An App Engine application for hosting static sites under multiple domains in a single app.
Python
66
star
23

django-tokenauth

Django authentication backend that uses tokens sent over email.
Python
63
star
24

arduino-irrigation

A GSM-based Arduino remote controller for an irrigation system.
Arduino
62
star
25

esplights

A home automation sensor and controller based on an ESP8266.
Arduino
48
star
26

yeecli

A command-line utility for a YeeLight RGB lamp. (mirror of https://gitlab.com/stavros/yeecli)
Python
42
star
27

episode-renamer

Episode renamer is a simple python script that renames folders of TV episode video files to their proper names.
Python
41
star
28

kicad-lib

My KiCad components library.
35
star
29

Spamnesty

A service that tries to have some fun with spam (mirror of https://gitlab.com/stavros/Spamnesty/)
Python
33
star
30

captainwebhook

Captain Webhook eats webhooks and executes commands.
Python
30
star
31

spamgpt

SpamGPT, a bot that wastes spammers' damn time, like they waste mine.
Python
25
star
32

pastebinit

pastebinit is a command-line tool to send data to a "pastebin", a web site which allows its users to upload snippets of text for public viewing. ⛺
Python
25
star
33

apache-config

A script for configuring apache with Django+wsgi/fcgi+virtualenv+etc.
Python
23
star
34

ArduiRC

Remotely control IR/RF devices from a computer with Arduino.
Arduino
18
star
35

docker-fgallery

A Dockerfile for installing fgallery. ⛺
Shell
18
star
36

ez-openai

Ez API, ez life.
Python
16
star
37

landing-page

A very simple landing page app for AppEngine.
Python
15
star
38

stringphone

String phone is a secure communications protocol and library geared towards embedded devices.
Python
14
star
39

bakeit

A command-line utility for pastery, the best pastebin in the world.
Python
12
star
40

pythess-files

The code files/presentations/everything else used in the PyThess meetup
Jupyter Notebook
11
star
41

lektor-shortcodes

A shortcodes plugin for lektor
Python
11
star
42

shufflecast

A TV channel with all your favorite shows.
Python
11
star
43

photocopy

A script to archive photos off a camera to a directory.
Python
10
star
44

nxt-python

NXT-Python is a python driver/interface for the Lego Mindstorms NXT robot based on NXT_python.
Python
10
star
45

Reverend

A clone of Reverend, the naive Bayesian classifier written in Python.
Python
10
star
46

A6-ESP8266-breakout

A breakout board that includes an ESP8266 and an A6 GSM module, for easily making GSM-enabled applications (mirror)
Shell
9
star
47

Pythia

High quality & fast "true random" number generator (shuffling system)
JavaScript
9
star
48

lektor-thumbnail-generator

A thumbnail generator for Lektor content
Python
9
star
49

pastery.vim

A Vim plugin for the sweetest pastebin in the world, pastery.net.
Vim Script
9
star
50

apt-btrfs-snapshot

A fork of apt-btrfs-snapshot.
Python
8
star
51

gamelights

An RGB LED strip WiFi controller, complete with code and PCB designs.
KiCad Layout
8
star
52

mediacenter-in-a-box

A media center in a box, compatible with Harbormaster for one-line deployments.
Python
8
star
53

pylast

A clone of Amr Hassan's pylast: a python interface to last.fm (and other api-compatible websites)
Python
6
star
54

awesomeblog-club

An easily self hostable curation site for collecting blogs and links.
TypeScript
5
star
55

django-project-templates

Some Django project templates for various things.
4
star
56

requests-guard

requests-guard is a small library that allows you to impose size and time limits on your HTTP requests.
Python
4
star
57

ChatGPT-Bot

A small Python library that makes it easier to write a ChatGPT bot.
Python
4
star
58

rust-bakeit

A command-line client for pastery.net, the best pastebin in the world (official mirror of https://gitlab.com/stavros/rust-bakeit).
Rust
3
star
59

the-spam-chronicles

The Spam Chronicles, a static website where I post all the spam I got and SpamGPT auto-replied to.
Python
2
star
60

progress

A simple progress bar in Python
Python
2
star
61

blacklist-pre-commit-hook

A pre-commit hook for blacklisting certain functions
Python
2
star
62

back-scratcher

A back scratching robot!
Python
2
star
63

zulipbot

A ChatGPT Zulip bot
Python
1
star
64

iphoneconverter

A small script to convert a folder of videos into an iPhone format.
1
star
65

reddit-rage-faces

An Opera extension to put ragefaces in every subreddit.
JavaScript
1
star