1 # Licensed to the Apache Software Foundation (ASF) under one or more
2 # contributor license agreements. See the NOTICE file distributed with
3 # this work for additional information regarding copyright ownership.
4 # The ASF licenses this file to You under the Apache License, Version 2.0
5 # (the "License"); you may not use this file except in compliance with
6 # the License. You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 UUID generation utilities.
20 from __future__ import absolute_import # so we can import standard 'uuid'
22 from random import randrange
23 from uuid import uuid4
25 from shortuuid import ShortUUID
28 # Alphanumeric without visually ambiguous characters; default length is 22
29 UUID_BASE57 = ShortUUID()
31 # Lower-case alphanumeric; default length is 25
32 UUID_LOWERCASE_ALPHANUMERIC = ShortUUID(alphabet='abcdefghijklmnopqrstuvwxyz0123456789')
35 def generate_uuid(length=None, variant='base57'):
37 A random string with varying degrees of guarantee of universal uniqueness.
40 * ``base57`` (the default) uses a mix of upper and lowercase alphanumerics ensuring no visually
41 ambiguous characters; default length 22
42 * ``alphanumeric`` uses lowercase alphanumeric; default length 25
43 * ``uuid`` uses lowercase hexadecimal in the classic UUID format, including dashes; length is
45 * ``hex`` uses lowercase hexadecimal characters but has no guarantee of uniqueness; default
49 if variant == 'base57':
50 the_id = UUID_BASE57.uuid()
51 if length is not None:
52 the_id = the_id[:length]
54 elif variant == 'alphanumeric':
55 the_id = UUID_LOWERCASE_ALPHANUMERIC.uuid()
56 if length is not None:
57 the_id = the_id[:length]
59 elif variant == 'uuid':
62 elif variant == 'hex':
64 # See: http://stackoverflow.com/a/2782859
65 the_id = ('%0' + str(length) + 'x') % randrange(16 ** length)
68 raise ValueError('unsupported UUID variant: {0}'.format(variant))