How to make unique short URL with Python?

Viewed 38816
12 Answers

Python's short_url is awesome.

Here is an example:

import short_url

id = 20  # your object id
domain = 'mytiny.domain' 

shortened_url = "http://{}/{}".format(
                                     domain,
                                     short_url.encode_url(id)
                               )

And to decode the code:

decoded_id = short_url.decode_url(param)

That's it :)

Hope this will help.

This module will do what you want, guaranteeing that the string is globally unique (it is a UUID):

http://pypi.python.org/pypi/shortuuid/0.1

If you need something shorter, you should be able to truncate it to the desired length and still get something that will reasonably probably avoid clashes.

You can generate a N random string:

import string
import random

def short_random_string(N:int) -> str:

    return ''.join(random.SystemRandom().choice(
        string.ascii_letters + \
        string.digits) for _ in range(N)
    )

so,

print (short_random_string(10) )
#'G1ZRbouk2U'

all lowercase

print (short_random_string(10).lower() )
#'pljh6kp328'
Related