Today we’re going to create a function that you can use in your applications that involves giving users temporary password.
It’s not limited to password generation though, you can use this function to generate a meal ticket or transaction number, etc.
By the way, this assumes you have read the previous blog. If not, here’s the link to that:
The function itself is small and most of the magic is performed by Pythons functions, we simply glued them together to solve a specific problem — generating random string (of certain length), and the use case for this is password generation.
def generate_random_string(length=6):
charset = string.ascii_letters + string.digits + string.punctuation
pwd = []
for i in range(length):
pwd.append(random.choice(charset))
return ''.join(pwd)
By the way, the full source code with comments is on my GitHub page and the link will be at the end of this blog (so you can download it and see the comments)
And here’s a basic demo of using this function:
def _demo():
""" a function to test the 'generate_random_string' function """
# define random length for testing
test_lengths = [4, 6 ,10, 16]
for pl in test_lengths:
# generate random strings based on password length 'pl'
pwd = generate_random_string(pl)
# output the result
print(f"Length of {pl} = {pwd}")
if __name__ == '__main__':
# only execute the sample code if run by itself (and not imported from another module)
_demo()
When you run this, you’ll get different results (since that’s the goal, make random strings).
Here’s what I get from my test:
Length of 4 = aHzq
Length of 6 = Eix;\]
Length of 10 = 1zV^OYWgR#
Length of 16 = rhN#uTf4ozRvzvX#
If you don’t want to include the punctuations, just remove it from the character set and that’ll be it.
Here’s the link to the source codes:
https://github.com/vegitz/codes/tree/master/0011%20Password%20Generator%20in%20Python