from dbsettings.functions import getValue from random import SystemRandom import baluhn def generate_voucher_code(prefix=getValue("payment.voucher.prefix", "9011"), length=getValue("payment.voucher.length", 16)): if length <= len(str(prefix)): raise ValueError("Voucher code length must be longer than its prefix!") length_randpart = length - len(str(prefix)) - 1 base_code = prefix for i in range(length_randpart): base_code += str(SystemRandom().randint(0, 9)) return baluhn.generate(base_code)