Hello By using python language, what would be a clever / efficient way of generating promotion codes. Like to be used for generating special numbers for discount coupons. like: 1027828-1
Thanks
Hello By using python language, what would be a clever / efficient way of generating promotion codes. Like to be used for generating special numbers for discount coupons. like: 1027828-1
Thanks
if you need a 6-digit # you could do this until you found a unique value:
import random
print str(random.randint(100000, 999999))
or go sequentially...
1027828-1 is extremely small. An attacker can make a ~million guesses using only a couple lines of code and maybe a few days.
This is a good way to produce a hard to predict number using python, it works under linux and windows. It is base64'ed for binary safety, depending what you are doing with it you might want to urllib.urlencode() but I would avoid base10 because it doesn't store as much information.
import os
import base64
def secure_rand(len=8):
token=os.urandom(len)
return base64.b64encode(token)
print(secure_rand())
As a side note this is generating a full byte, which is base256. 256^8 is 18446744073709551616 which should be large enough.
The following isn't particularly pythonic or particularly efficient, but it might suffice:
import random
def get_promo_code(num_chars):
code_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
code = ''
for i in range(0, num_chars):
slice_start = random.randint(0, len(code_chars) - 1)
code += code_chars[slice_start: slice_start + 1]
return code