Tips on how to create an Picture Host Filename Generator in Python



The problem

You’re growing a picture internet hosting web site.

It’s important to create a perform for producing random and distinctive picture filenames.

Create a perform for producing a random 6 character string that shall be used to entry the photograph URL.

To verify the identify will not be already in use, you’re given entry to a PhotoManager object.

You possibly can name it like so to ensure the identify is exclusive

# at this level, the web site has just one photograph, hosted on the 'ABCDEF' url
photoManager.nameExists('ABCDEF'); # returns true
photoManager.nameExists('BBCDEF'); # returns false

Observe: We think about two names with the identical letters however totally different circumstances to be distinctive.

The answer in Python code

Choice 1:

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

Choice 2:

from random import pattern
from string import ascii_letters

def generateName(size=6):
    whereas True:
        identify = ''.be part of(pattern(ascii_letters, size))
        if not photoManager.nameExists(identify):
            return identify

Choice 3:


Take a look at circumstances to validate our answer

for i in vary(10):
    identify = generateName();

    check.count on(isinstance(identify, str), "Title needs to be a string.");
    check.count on(photoManager.nameWasUnique(identify), "Title needs to be distinctive.");
    check.assert_equals(len(identify), 6, "Title needs to be 6 digits lengthy.");