Creating A Simple Web App With Flask

Creating a Simple Web App with Flask

If you’re into Python programming, chances are you’ve heard of Flask. Flask is a micro web framework written in Python that allows you to build web applications quickly and easily. In this tutorial, we’ll take a look at how to create a simple web app using Flask.


Creating A Simple Web App With Flask
Creating A Simple Web App With Flask

Getting Started with Flask

Before we dive into creating our web app, let’s make sure we have Flask installed. You can install Flask using pip, the package installer for Python. Open up your terminal or command prompt and run the following command:

pip install flask

Once Flask is installed, we can start creating our web app.

Setting Up the Project

First, let’s create a new directory for our project. In your terminal or command prompt, navigate to the directory where you want to create the project and run the following command:

mkdir flask-web-app

Next, navigate into the newly created directory:

cd flask-web-app

Inside the flask-web-app directory, create a new Python file called app.py using your favorite text editor.

Importing Flask and Creating an App

In app.py, we need to import Flask and create an instance of the Flask class. Add the following code to your app.py file:

from flask import Flask

app = Flask(__name__)

In the above code, we import the Flask class from the flask module and create a new instance of the Flask class. We pass __name__ as the parameter, which is a special variable that gets the name of the module. This is necessary so that Flask knows where to find the static and template files.

Creating the Homepage

Now that we have our Flask app set up, let’s create a simple homepage. We can do this by defining a route and a view function. In Flask, a route maps a URL to a view function. The view function is responsible for returning a response to that URL.

Add the following code to your app.py file to create a route for the homepage:

@app.route('/')
def home():
    return 'Welcome to the homepage!'

In the above code, @app.route('/') is a decorator that tells Flask which URL should trigger our home function. The home function simply returns the string 'Welcome to the homepage!'.

To run our app, add the following code to the bottom of app.py:

if __name__ == '__main__':
    app.run(debug=True)

The if __name__ == '__main__': block checks if the script is being run directly, and if so, it starts the Flask development server.

To start the server, navigate to the flask-web-app directory in your terminal or command prompt and run the following command:

python app.py

You should see some output indicating that the Flask development server has started. Open your web browser and navigate to http://localhost:5000 to see your homepage.

Adding Additional Routes

Now that we have our homepage set up, let’s create some additional routes. Routes allow us to handle different URLs and return different responses.

Let’s create a route for an About page. Add the following code to your app.py file:

@app.route('/about')
def about():
    return 'This is the about page!'

In the above code, we define a route for '/about' and a corresponding view function named about, which returns the string 'This is the about page!'.

To test your new route, stop the Flask development server by pressing Ctrl + C in your terminal or command prompt and restart it by running python app.py again. Open your web browser and navigate to http://localhost:5000/about.

You should now see the text 'This is the about page!'.

Templates and Rendering HTML

While returning plain text strings from our view functions is fine, it’s usually more useful to return HTML templates. Flask has built-in support for rendering templates using Jinja2, a modern and designer-friendly templating language for Python.

First, create a new directory called templates inside your flask-web-app directory. This is where we’ll store our HTML templates.

Inside the templates directory, create a new file called index.html. Open index.html in your text editor and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Flask Web App</title>
</head>
<body>
    <h1>Welcome to the Flask Web App</h1>
    <p>This is the homepage!</p>
</body>
</html>

Now, let’s modify the home view function in app.py to render this template instead of returning a plain text string:

from flask import render_template

@app.route('/')
def home():
    return render_template('index.html')

In the above code, we import the render_template function from the flask module and modify the home view function to return the result of calling render_template('index.html'). This tells Flask to render the index.html template.

Restart the Flask development server and navigate to http://localhost:5000 in your web browser. You should now see the HTML content defined in index.html.

Passing Data to Templates

In addition to rendering static HTML content, we can also pass data to templates to make them dynamic. Let’s modify our about view function to pass some data to a new template called about.html.

First, create a new file called about.html inside the templates directory. Open about.html in your text editor and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>About</title>
</head>
<body>
    <h1>About Page</h1>
    <p>{{ description }}</p>
</body>
</html>

In the code above, we use the double curly braces {{ }} to insert a placeholder for the description variable.

Now, modify the about view function in app.py to pass a description to the about.html template:

@app.route('/about')
def about():
    description = 'This is the about page!'
    return render_template('about.html', description=description)

In the code above, we modify the about view function to assign a value to the description variable and pass it to the about.html template using the render_template function.

Restart the Flask development server and navigate to http://localhost:5000/about. You should now see the text 'This is the about page!' rendered on the page.

Handling Form Submissions

In addition to rendering templates, Flask also provides functionality for handling form submissions. Let’s create a simple contact form and handle the form submission.

First, create a new file called contact.html inside the templates directory. Open contact.html in your text editor and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Contact</title>
</head>
<body>
    <h1>Contact</h1>
    <form method="POST" action="/contact">
        <input type="text" name="name" placeholder="Name" required><br>
        <input type="email" name="email" placeholder="Email" required><br>
        <textarea name="message" placeholder="Message" required></textarea><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

In the code above, we create a simple HTML form with fields for name, email, and message. The form method is set to "POST" and the action attribute is set to "/contact".

Now, let’s create a route that handles the form submission. Add the following code to app.py:

from flask import request

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        message = request.form['message']
        return f'Thank you, {name}! Your message has been sent.'
    return render_template('contact.html')

In the code above, we import the request object from the flask module. Inside the contact view function, we check if the request method is "POST". If it is, we retrieve the values of the form fields using request.form['name'], request.form['email'], and request.form['message']. We then return a thank you message. If the request method is "GET", we simply render the contact.html template.

Restart the Flask development server and navigate to http://localhost:5000/contact. You should see the contact form. Fill out the form and submit it. You should now see a thank you message with your name.

Conclusion

Congratulations! You’ve successfully created a simple web app using Flask. In this tutorial, you learned how to set up Flask, define routes and views, render HTML templates, pass data to templates, and handle form submissions. Flask provides a powerful and flexible framework for building web applications in Python.

Remember, this is just the beginning of what you can do with Flask. There are many more features and functionalities you can explore to build more complex web applications. So keep experimenting, and happy coding!

References:

  • Flask Documentation: https://flask.palletsprojects.com/
  • Jinja2 Documentation: https://jinja.palletsprojects.com/
Share this article:

Leave a Comment