Build a Random Password Generator Flask App in Python: Complete with Source Code! – 2024

Hey, guys in this blog we will see how we can build a Random Password Generator Flask App using Python.

In today’s digital age, having strong and unique passwords is crucial to protect our online accounts and sensitive information from unauthorized access. However, creating and remembering secure passwords for each website or service can be challenging. To simplify this process, we can leverage the power of Python and Flask to build a random password generator web application.

Sneak Peek at our Random Password Generator Flask App

main screen - Random Password Generator Flask App

Why use a random password generator?

Using a random password generator provides several benefits. Firstly, it ensures that the passwords generated are highly secure and difficult to guess, as they are not based on personal information or common patterns. Additionally, using unique passwords for each account enhances security by reducing the risk of multiple accounts being compromised if one password is exposed.

Working of our Random Password Generator Flask App

First of all, we need to give the required input which is the password length.

Then Our Random Password generator App comes with 4 variations to make even stronger passwords. Those 4 variations are:

  • Include Spaces
  • Include Numbers
  • Include Symbols
  • Include Uppercase Letters

We can use these variations in any combination.

Variations in our Random Password Generator Flask App

Password Length

  • This field is a mandatory field.
  • You need to provide the number of characters you need in your password.
  • By default, I have set the minimum to 8 and the maximum to 25 in the code. You can change that at any time.
  • Following is an example where I have deselected all the variations and entered 10 as the password length and you can see at the bottom, that we have got a 10-character password.
password length - Random Password Generator Flask App

Include Spaces

  • The first variation that we have is Include Spaces.
  • We can add spaces to our passwords to make them even stronger.
  • Following is an example where I have just selected Include Spaces and entered 10 as the password length and you can see at the bottom, that we have got a 10-character password with spaces included.
Machine Learning Projects

Include Numbers

  • The second variation that we have is Include Numbers.
  • We can add numbers to our passwords to make them even stronger.
  • Following is an example where I have just selected Include Numbers and entered 10 as the password length and you can see at the bottom, that we have got a 10-character password with numbers included.
Machine Learning Projects

Include Symbols

  • The second variation that we have is Include Symbols.
  • We can also add symbols to our passwords to make them even stronger.
  • Following is an example where I have just selected Include Symbols and entered 10 as the password length and you can see at the bottom, that we have got a 10-character password with symbols included.
Machine Learning Projects

Include Uppercase Letters

  • The second variation that we have is Include Uppercase Letters.
  • We can also add uppercase letters to our passwords to make them even stronger.
  • Following is an example where I have just selected Include Uppercase Letters and entered 10 as the password length and you can see at the bottom, that we have got a 10-character password with Uppercases included.
Machine Learning Projects

Source Code for Random Password Generator Flask App

app.py

# Random Password Generator Flask App

from flask import Flask,request,render_template
from datetime import date
import random
import string

#### Defining Flask App
app = Flask(__name__)


#### Saving Date today in 2 different formats
datetoday = date.today().strftime("%m_%d_%y")
datetoday2 = date.today().strftime("%d-%B-%Y")


################## ROUTING FUNCTIONS #########################

#### Our main page
@app.route('/')
def home():
    return render_template('home.html',datetoday2=datetoday2)


@app.route('/genpassword',methods=['GET','POST'])
def genpassword():
    minpasslen = 8
    maxpasslen = 30

    passlen = int(request.form.get('passlen'))

    if passlen<minpasslen:
        return render_template('home.html',datetoday2=datetoday2,mess=f'Atleast create a {minpasslen} digit password...')

    if passlen>maxpasslen:
        return render_template('home.html',datetoday2=datetoday2,mess=f'Can Create a max {maxpasslen} digit password...')

    include_spaces = request.form.get('includespaces')
    include_numbers = request.form.get('includenumbers')
    include_special_chars = request.form.get('includespecialchars')
    include_uppercase_letters= request.form.get('includeuppercaseletters')
    
    lowercase_letters = string.ascii_lowercase
    uppercase_letters = string.ascii_uppercase
    digits = string.digits
    special_chars = string.punctuation

    print(include_spaces,include_numbers,include_special_chars,include_uppercase_letters)

    char_sets = [lowercase_letters]

    # Add character sets based on the parameters
    if include_spaces=='on':
        char_sets.append(' ')
    if include_numbers=='on':
        char_sets.append(digits)
    if include_special_chars=='on':
        char_sets.append(special_chars)
    if include_uppercase_letters=='on':
        char_sets.append(uppercase_letters)

    # Combine the character sets
    all_chars = ''.join(char_sets)

    password = random.choices(all_chars, k=passlen)
    password = ''.join(password)


    return render_template('home.html',datetoday2=datetoday2,generatedpassword=password)


#### Our main function which runs the Random Password Generator Flask App
if __name__ == '__main__':
    app.run(debug=True)

home.html

Create a folder called templates and create a file inside that called ‘home.html’. The final folder structure should look like the below:

to-do list flask app in python folder structure

<!doctype html>
<html lang="en">

<style type='text/css'>
    * {
        padding: 0;
        margin: 0;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }


    body {
        background-image: url('https://cutewallpaper.org/21/1920-x-1080-gif/1920x1080-Wallpapercartoon-Wallpapers-Driverlayer-Search-.gif');
        background-size: cover;
        font-family: sans-serif;
        margin-top: 40px;
        height: 100vh;
        padding: 0;
        margin: 0;
    }

    table {
        border: 1px;
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 86%;
        margin: auto;
    }

    td,
    th {
        border: 1px solid black !important;
        padding: 5px;
    }

    tr:nth-child(even) {
        background-color: #dddddd;
    }
</style>


<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Random Password Generator</title>
</head>

<body>


    <div class='mt-1 text-center'>
        <h1 style="width: auto;margin: auto;color: white;padding: 20px;">Random Password Generator</h1>
    </div>

    <div class='mt-3 text-center'>
        <h3 style="font-size: 22px;color:beige;">{{ datetoday2 }} | <span id="clock"></span></h3>
    </div>

    {% if mess%}
    <p class="text-center" style="color: red;font-size: 20px;">{{ mess }}</p>
    {% endif %}

    <div class="row text-center" style="padding: 20px;margin: 20px;">

        <div class="col"
            style="border-radius: 20px;padding: 0px;background-color:rgb(211,211,211,0.5);margin:0px 10px 10px 10px;min-height: 400px;">
            <h2 style="border-radius: 20px 20px 0px 0px;background-color: #0b4c61;color: white;padding: 10px;">Random
                password Generator </h2>

            <form action='/genpassword' method="POST" enctype="multipart/form-data">
                <label style="font-size: 20px;"><b>Enter Password Length*</b></label>
                <br>
                <input type="text" id="passlen" name='passlen'
                    style="font-size: 20px;margin-top:10px;margin-bottom:10px;" required>
                <br>
                <div class="container" style="width: 270px;text-align: left;">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="includespaces" id="includespaces" checked>
                        <label class="form-check-label" for="flexCheckChecked">Include Spaces</label>
                    </div>

                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="includenumbers" id="includenumbers"
                            checked>
                        <label class="form-check-label" for="flexCheckChecked">Include Numbers</label>
                    </div>

                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="includespecialchars"
                            id="includespecialchars" checked>
                        <label class="form-check-label" for="flexCheckChecked">Include Symbols</label>
                    </div>

                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="includeuppercaseletters"
                            id="includeuppercaseletters" checked>
                        <label class="form-check-label" for="flexCheckChecked">Include UpperCase Letters</label>
                    </div>
                </div>
                <button style="width: 232px;margin-top: 20px;font-size: 20px;" type='submit'
                    class='btn btn-success'>Generate Password
                </button>
                <br>
            </form>

            {% if generatedpassword %}
            <div>
                <h3 class="text-center" style="font-size: 25px;">Generated Password:</h3>
                <h4 class="text-center" style="font-size: 25px;"><b>{{ generatedpassword }}</b></h4>
            </div>
            {% endif %}

        </div>
        

    </div>

    <script type="text/javascript">
        var clockElement = document.getElementById('clock');

        function clock() {
            clockElement.textContent = new Date().toString().slice(15, 24);
        }

        setInterval(clock, 1000);
    </script>

</body>

</html>

Download Source Code

Conclusion

Building a random password generator Flask app in Python allows us to create a user-friendly interface for generating strong and secure passwords. By leveraging Flask’s simplicity and Python’s randomization capabilities, we can develop a robust application that enhances online security. Remember to always prioritize the protection of your digital assets by using strong and unique passwords.

So this is how you can code a Random Password Generator Flask App in Python. If you have any doubt regarding this, you can contact me by mail.

FAQs

How secure are the passwords generated by this Random Password Generator Flask App?

The passwords generated by the app are highly secure. They are generated using Python’s random module. This ensures that the passwords are not predictable or easily guessable.

Can I customize the password generation criteria?

Yes, the app allows you to customize the password generation criteria. You can specify the desired password length, choose different character types (uppercase, spaces, digits, symbols), and include any additional requirements to suit your specific needs.

Is it possible to integrate the app with an existing website?

Absolutely! The Flask app can be integrated with an existing website by embedding it within a web page or linking to it from your site’s navigation. This allows your users to conveniently access the random password generator without leaving your website.

Can the app be used offline?

Yes, the app can run offline on localhost.

Are there any limitations to the password length or complexity?

The password length and complexity are customizable within reasonable limits. However, keep in mind that excessively long passwords may not be practical for some systems or websites that have restrictions on password length. It’s best to adhere to the specific requirements of the systems where you intend to use the generated passwords.

What are some of the best online password Random Password generators?

One online Random Password Generator that I think is best is Tools in Cloud’s Random Password Generator.

Read my last article – Create Your Own To-Do List Flask App Using Python

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projectsFlask projects at machinelearningprojects.net

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 514

Leave a Reply

Your email address will not be published. Required fields are marked *