Random Key Generation with Prefix

  • Share this:

Code introduction


This function generates a specified number of random keys, each starting with a given prefix and followed by a randomly generated string of a specified length as part of the key name.


Technology Stack : redis

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import redis

def random_key_generation(prefix, number_of_keys, length=10):
    """
    Generate a list of random keys with a given prefix and length.

    :param prefix: The prefix to be added to each generated key.
    :param number_of_keys: The number of keys to generate.
    :param length: The length of the random part of each key.
    :return: A list of generated keys.
    """
    keys = []
    for _ in range(number_of_keys):
        random_part = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=length))
        keys.append(f"{prefix}:{random_part}")
    return keys                
              
Tags: