How to Generate a Temporary Random Password in Python


In this article, we show how to generate a temporary random password in Python.

For many websites, a temporary random password may need to be used to give users access to an account.

You can generate a temporary random password like how you can generate any temporary string.

In our code below, we will generate a case-sensitive password that consists of all alphabetical characters, lowercase and uppercase, all numbers 0-9, and an _

I don't know if random passwords commonly contain any other type of characters, but if you want, you can easily add other characters.

So when designing a script for random passwords, you have to choose from a wide variety of characters to give a good set of possibilities and you have to choose a long-enough random string. We can't generate a random password that has 2 or 3 characters. It has to be long enough for a random password. In this example, we'll create a random password of 15 characters.

The code to do this is shown below.

So the following Python code above is able to generate an 15-character random temporary password from the characters we have provided in the characters variable. This characters variable contains 0-9,a-z,A-Z, and _

If you want any other characters to possibly be selected for representation in the temporarypassword, then just add it to the characters string.

So the first thing we must do in our code is import the random module.

We then have a variable named characters, which we set equal to, 0-9,a-z,A-Z, and _

We then create the variable, temporarypassword, which will be the variable that represents the 15-character random temporary password in the end.

We then create a for loop that has 15 iterations, from 0 to 14; thus, a 15-character output will be the result. If you want a 12-character random string, then you change 15 to 12. If you want a 20-character random string, then you change 15 to 20 (even though that's probably overkill for a temporary password length).

We then set the randomstring variable equal to += random.choice(characters).

What this line does is it selects a random character from the characters variable for each of the 15 characters we make of the random string.

And this is all that is required to generate a random temporary password in Python.

Related Resources

How to Insert Images into a Database Table with Python in Django

How to Insert Files into a Database Table with Python in Django

How to Insert Videos into a Database Table with Python in Django

HTML Comment Box is loading comments...