Skip to content

Instantly share code, notes, and snippets.

@Louis95
Created August 9, 2020 03:41
Show Gist options
  • Save Louis95/64030d7e155c13b89962b6bb65ade4a6 to your computer and use it in GitHub Desktop.
Save Louis95/64030d7e155c13b89962b6bb65ade4a6 to your computer and use it in GitHub Desktop.
A gift card generator using the python secrets module and timestamp to generate cryptographically strong random gift card codes
import time
import string
import secrets
'''
The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords,
account authentication, security tokens, and related secrets.
'''
def generateGiftCardCodes():
seconds = time.time()
unix_time_to_string = str(seconds).split('.')[0] #time.time() generates a float example 1596941668.6601112
alphaNumeric = string.ascii_uppercase + unix_time_to_string
firstSet = ''.join(secrets.choice(alphaNumeric) for i in range(4))
secondSet = ''.join(secrets.choice(alphaNumeric) for i in range(4))
thirdSet = ''.join(secrets.choice(alphaNumeric) for i in range(4))
giftCardCode = firstSet + "-" + secondSet + "-" + thirdSet
# return giftCardCode
print(giftCardCode)
print("Please enter the number of gift codes you want to generate")
num = int(input("Enter: "))
for i in range(num):
generateGiftCardCodes()
@S3wnkin
Copy link

S3wnkin commented Nov 23, 2022

This is a much better approach:

import secrets
import string


def gen_rnd_string(
    n: int = 4
) -> str:
    return ''.join(
        secrets.choice(
            string.ascii_uppercase + string.digits
        )
        for _ in range(n)
    )


def generate_gift_card(
    n: int = 4
) -> str:
    return "-".join(
        gen_rnd_string() for _ in range(n)
    )


if __name__ == "__main__":
    gift_code = generate_gift_card()

    print(gift_code)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment