Learn how to create an Picture Host Filename Generator in Python



The problem

You’re growing a picture internet hosting web site.

You must create a perform for producing random and distinctive picture filenames.

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

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

You’ll be able to name it like so to ensure the identify is exclusive

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

Notice: We contemplate two names with the identical letters however completely 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 a part of(pattern(ascii_letters, size))
        if not photoManager.nameExists(identify):
            return identify

Choice 3:


Check circumstances to validate our resolution

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

    take a look at.anticipate(isinstance(identify, str), "Title must be a string.");
    take a look at.anticipate(photoManager.nameWasUnique(identify), "Title must be distinctive.");
    take a look at.assert_equals(len(identify), 6, "Title must be 6 digits lengthy.");