Python for Web Development: Building a Flask Application

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up
  4. Creating a Flask Application
  5. Routing and Handling Requests
  6. Rendering Templates
  7. Adding Forms and User Input
  8. Working with Databases
  9. Deployment
  10. Conclusion

Introduction

In this tutorial, we will learn how to build a web application using Flask, a popular Python web framework. By the end of this tutorial, you will be able to create your own Flask application and understand the basics of web development with Python.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming. Familiarity with concepts like functions, variables, and control flow will be beneficial. Additionally, you should have Python and Flask installed on your machine.

Setting Up

Before we can start building our Flask application, we need to set up our development environment. Follow these steps to get started:

  1. Open your terminal or command prompt.
  2. Create a new directory for your project: mkdir flask-app
  3. Navigate into the project directory: cd flask-app
  4. Create a virtual environment: python3 -m venv venv
  5. Activate the virtual environment:
    • For Mac/Linux: source venv/bin/activate
    • For Windows: venv\Scripts\activate
  6. Install Flask: pip install flask

With the setup complete, we are ready to start building our Flask application.

Creating a Flask Application

Let’s create a simple “Hello, World!” application to get familiar with Flask.

  1. Create a new Python file in your project directory, e.g., app.py
  2. Open the file with your preferred text editor.
  3. Import the Flask module: from flask import Flask
  4. Create an instance of the Flask class: app = Flask(__name__)
  5. Define a route and a handler function to handle requests:
    @app.route('/')
    def hello():
        return "Hello, World!"
    
  6. Add a conditional check to ensure the app is run directly:
    if __name__ == '__main__':
        app.run()
    

    Save the file and return to your terminal. Start the Flask development server by running python app.py. You should see a message indicating that the server is running. Open your web browser and navigate to http://localhost:5000. You should see the “Hello, World!” message displayed on the page.

Routing and Handling Requests

In Flask, routes are used to map URLs to handler functions. Let’s create some additional routes and handle different types of requests.

  1. Define a new route for a contact page:
    @app.route('/contact')
    def contact():
        return "Contact Us"
    
  2. Add a route that accepts a dynamic parameter:
    @app.route('/hello/<name>')
    def say_hello(name):
        return f"Hello, {name}!"
    
  3. Create a route that handles POST requests:
    @app.route('/login', methods=['POST'])
    def login():
        username = request.form.get('username')
        password = request.form.get('password')
        # Check username and password
        # ...
        return "Logged in successfully"
    

    By adding these routes and handler functions to your app.py file, you can now navigate to http://localhost:5000/contact to see the “Contact Us” page, or http://localhost:5000/hello/John to greet the name “John”. Additionally, you can create an HTML form that submits a POST request to http://localhost:5000/login and receive a “Logged in successfully” response.

Rendering Templates

Flask allows you to separate your application logic from your HTML templates. Let’s create a template for our “Hello, World!” page.

  1. Create a new directory inside your project directory called templates.
  2. Inside the templates directory, create a new file called hello.html.
  3. Open hello.html and add the following content:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Hello Flask</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
    </html>
    
  4. Update your app.py file to render the template:
    from flask import render_template
       
    @app.route('/')
    def hello():
        return render_template('hello.html')
    

    Save both files and restart the Flask server. If you navigate to http://localhost:5000, you will see the same “Hello, World!” message, but this time it is rendered from the HTML template.

Adding Forms and User Input

One common requirement in web applications is to accept user inputs via forms. Flask makes it easy to handle form submissions.

  1. Create a new template called login.html in the templates directory.
  2. Add a login form to the login.html template:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Login</title>
    </head>
    <body>
        <h1>Login</h1>
        <form action="/login" method="POST">
            <input type="text" name="username" placeholder="Username">
            <input type="password" name="password" placeholder="Password">
            <input type="submit" value="Login">
        </form>
    </body>
    </html>
    
  3. Update your app.py file to render the login.html template for the /login route.

Now, when you navigate to http://localhost:5000/login, you will see a login form. When you submit the form, the data will be sent as a POST request to the /login route, where you can access the form inputs and perform any necessary processing.

Working with Databases

To build more complex web applications, we often need to store and retrieve data from a database. Flask integrates well with various database systems.

  1. Install the Flask-SQLAlchemy extension: pip install flask_sqlalchemy
  2. Add a configuration to your app.py file to specify the database URL:
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
    
  3. Create a new directory called models in your project directory.
  4. Inside the models directory, create a new file called user.py.
  5. Define a User model in user.py using SQLAlchemy:
    from flask_sqlalchemy import SQLAlchemy
       
    db = SQLAlchemy()
       
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50), nullable=False)
        email = db.Column(db.String(50), nullable=False, unique=True)
       
        def __repr__(self):
            return f"<User {self.name}>"
    
  6. Initialize the database in your app.py file:
    from models.user import db
       
    db.init_app(app)
    
  7. Create a new route to handle user registration:
    @app.route('/register', methods=['GET', 'POST'])
    def register():
        if request.method == 'POST':
            name = request.form.get('name')
            email = request.form.get('email')
            user = User(name=name, email=email)
            db.session.add(user)
            db.session.commit()
            return "User registered successfully"
        return render_template('register.html')
    

    Now, whenever a user submits the registration form, their information will be stored in the database. You can retrieve and query the user data as needed.

Deployment

To make your Flask application accessible over the internet, you need to deploy it on a web server. There are various hosting options available, including cloud platforms and traditional web hosts.

One popular option is to deploy on a Platform-as-a-Service (PaaS) provider like Heroku. Follow these steps to deploy your Flask application on Heroku:

  1. Create a Heroku account (if you don’t have one already).
  2. Install the Heroku CLI by following the instructions on the Heroku website.
  3. Log in to the Heroku CLI using the command heroku login.
  4. In your project directory, create a new file called Procfile and add the following content:
    web: gunicorn app:app
    
  5. Initialize a new Git repository and commit your code.
  6. Create a new Heroku app using the command heroku create.
  7. Push your code to the Heroku remote repository using git push heroku master.
  8. After the deployment process completes, you can access your Flask application using the URL provided by Heroku.

Congratulations! You have successfully deployed your Flask application to a live web server.

Conclusion

In this tutorial, we covered the basics of building a Flask application for web development. We started by setting up our development environment, creating routes, and handling different types of requests. We then explored rendering templates, accepting user inputs through forms, and integrating with databases. Finally, we learned how to deploy our Flask application to a web server.

Flask is a versatile web framework that offers many features and extensions, making it an excellent choice for building web applications with Python. With the knowledge gained from this tutorial, you can continue exploring Flask and its ecosystem to create more complex and feature-rich web applications.

Remember to refer to the Flask and SQLAlchemy documentation for more detailed information on specific topics and to expand your web development skills further.