Introduction to Flask: Routes, Templates, and Flask-SQLAlchemy

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Flask Routes
  5. Templates
  6. Flask-SQLAlchemy
  7. Conclusion

Introduction

In this tutorial, we will explore the fundamentals of Flask, a micro web framework for Python. We will cover Flask routes, which define the URLs that our application will respond to, and how to use templates to build dynamic HTML pages. Additionally, we will integrate Flask with SQLAlchemy, a popular Python SQL toolkit, to interact with a database.

By the end of this tutorial, you will have a good understanding of how to create routes, utilize templates for rendering dynamic content, and perform database operations using Flask-SQLAlchemy.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming. Knowledge of HTML and SQL will also be beneficial. It is recommended to have Python and Flask installed on your system.

Setup

To get started, let’s set up a new Flask project. Follow these steps:

  1. Create a new directory for your project and navigate into it using the terminal or command prompt:
     mkdir flask_project
     cd flask_project
    
  2. Create a virtual environment to isolate your project’s dependencies:
     python -m venv venv
    
  3. Activate the virtual environment:
     source venv/bin/activate    # For Mac/Linux
     venv\Scripts\activate      # For Windows
    
  4. Install Flask:
     pip install flask
    

    Now we are ready to start building our Flask application!

Flask Routes

Flask routes define the mapping between the URLs and the Python functions that handle the corresponding requests. Let’s create a simple Flask route.

  1. Create a new file named app.py in your project directory:
     touch app.py
    
  2. Open app.py in a text editor and import Flask:
     from flask import Flask
    
  3. Initialize the Flask application:
     app = Flask(__name__)
    
  4. Define a route and a function to handle the request:
     @app.route('/')
     def home():
         return 'Hello, Flask!'
    

    The @app.route('/') decorator maps the URL / to the home() function. When a user visits the root URL of our application, the home() function will be executed, and the string 'Hello, Flask!' will be returned to the user’s browser.

  5. Add a main section to run the Flask application:
     if __name__ == '__main__':
         app.run(debug=True)
    
  6. Save the file and run the application:
     python app.py
    
  7. Open your browser and visit http://127.0.0.1:5000. You should see the message “Hello, Flask!” displayed.

Congratulations! You have created your first Flask route. Let’s move on to using templates to render HTML pages.

Templates

Templates allow us to separate the presentation logic from the application logic. Flask uses the Jinja2 templating engine to render dynamic HTML pages.

  1. Create a new directory named templates in your project directory:
     mkdir templates
    
  2. Create a new file named index.html inside the templates directory, and open it in a text editor:
     touch templates/index.html
    
  3. In index.html, add the following HTML code:
     <!DOCTYPE html>
     <html>
     <head>
         <title>Flask Template</title>
     </head>
     <body>
         <h1>Welcome to Flask Template!</h1>
         <p></p>
     </body>
     </html>
    
  4. Modify the home() function in app.py to render the template:
     from flask import render_template
    	
     @app.route('/')
     def home():
         return render_template('index.html', message='Hello, Flask!')
    

    The render_template() function takes the name of the template file as the first argument and any additional data to pass to the template as keyword arguments. In this case, we are passing the message 'Hello, Flask!' to be displayed in the template.

  5. Save the changes and run the application again:
     python app.py
    
  6. Refresh your browser at http://127.0.0.1:5000, and you should now see the heading “Welcome to Flask Template!” and the message “Hello, Flask!”.

Amazing! You have successfully rendered an HTML template using Flask. Let’s now integrate Flask with SQLAlchemy to work with a database.

Flask-SQLAlchemy

Flask-SQLAlchemy is an extension that provides simple integration of SQLAlchemy with Flask. SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for Python.

  1. Install Flask-SQLAlchemy:
     pip install flask_sqlalchemy
    
  2. In app.py, import FlaskSQLAlchemy and initialize it:
     from flask_sqlalchemy import SQLAlchemy
    	
     app = Flask(__name__)
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'   # SQLite database file path
     db = SQLAlchemy(app)
    
  3. Define a model class for your database table. For example, let’s create a User model:
     class User(db.Model):
         id = db.Column(db.Integer, primary_key=True)
         name = db.Column(db.String(50), nullable=False)
    
  4. Create the database tables by running the following commands:
     python
     from app import db
     db.create_all()
    

    This will create a file named database.db in your project directory, which will hold the database tables.

  5. Perform database operations inside Flask routes. Here’s an example of handling a POST request to create a new user:
     from flask import request
    	
     @app.route('/user', methods=['POST'])
     def create_user():
         name = request.form['name']
         user = User(name=name)
         db.session.add(user)
         db.session.commit()
         return 'User created successfully'
    

    In this example, we access the form data submitted in the POST request using request.form['name'] and create a new User object with the provided name. We then add the user to the database session, commit the changes, and return a success message.

  6. Remember to import the required modules and include the necessary HTML forms in your templates.

Congratulations! You have integrated Flask with SQLAlchemy to perform database operations. Feel free to explore more advanced features of Flask and SQLAlchemy to build powerful web applications.

Conclusion

In this tutorial, we have covered Flask routes, templates, and Flask-SQLAlchemy. We learned how to define routes in Flask, use templates to render dynamic HTML pages, and integrate Flask with SQLAlchemy for database operations. By following this tutorial, you should now have a solid foundation to start building your own Flask applications.

Remember to practice and explore additional resources to further enhance your skills in Flask and web development with Python. Happy coding!