How to Create an Image Host Filename Generator in Python


The challenge

You are developing an image hosting website.

You have to create a function for generating random and unique image filenames.

Create a function for generating a random 6 character string that will be used to access the photo URL.

To make sure the name is not already in use, you are given access to a PhotoManager object.

You can call it like so to make sure the name is unique

# at this point, the website has only one photo, hosted on the 'ABCDEF' url
photoManager.nameExists('ABCDEF'); # returns true
photoManager.nameExists('BBCDEF'); # returns false

Note: We consider two names with the same letters but different cases to be unique.

The solution in Python code

Option 1:

import uuid
def generateName():
    return str(uuid.uuid4())[:6]

Option 2:

from random import sample
from string import ascii_letters

def generateName(length=6):
    while True:
        name = ''.join(sample(ascii_letters, length))
        if not photoManager.nameExists(name):
            return name

Option 3:

generateName=lambda:str(__import__("time").time())[-6:]

Test cases to validate our solution

for i in range(10):
    name = generateName();

    test.expect(isinstance(name, str), "Name has to be a string.");
    test.expect(photoManager.nameWasUnique(name), "Name has to be unique.");
    test.assert_equals(len(name), 6, "Name has to be 6 digits long.");