In this section, we will guide you through creating your first Flask application. By the end of this lesson, you will have a basic Flask app running on your local machine. This will serve as the foundation for more complex applications you'll build in later modules.

Step-by-Step Guide

  1. Setting Up Your Project Directory

First, create a new directory for your Flask project. Open your terminal or command prompt and run the following commands:

mkdir my_flask_app
cd my_flask_app

  1. Creating a Virtual Environment

It's a good practice to create a virtual environment for your project to manage dependencies. Run the following commands:

python -m venv venv

Activate the virtual environment:

  • On Windows:
    venv\Scripts\activate
    
  • On macOS/Linux:
    source venv/bin/activate
    

  1. Installing Flask

With the virtual environment activated, install Flask using pip:

pip install Flask

  1. Creating the Flask Application

Create a new file named app.py in your project directory. This file will contain the code for your Flask application.

# app.py

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

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

Explanation:

  • Importing Flask: The from flask import Flask line imports the Flask class.
  • Creating an Instance: app = Flask(__name__) creates an instance of the Flask class. The __name__ variable is a special Python variable that gets the name of the module.
  • Defining a Route: The @app.route('/') decorator defines a route for the home page. The home function returns a simple string "Hello, Flask!".
  • Running the App: The if __name__ == '__main__': block ensures that the app runs only if the script is executed directly, not when imported as a module. app.run(debug=True) starts the Flask development server with debug mode enabled.

  1. Running the Application

To run your Flask application, execute the following command in your terminal:

python app.py

You should see output similar to this:

 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 123-456-789

Open your web browser and navigate to http://127.0.0.1:5000/. You should see the message "Hello, Flask!".

Practical Exercise

Exercise 1: Modify the Home Route

Modify the home function to return a different message, such as "Welcome to My First Flask App!".

Solution:

@app.route('/')
def home():
    return "Welcome to My First Flask App!"

Exercise 2: Add a New Route

Add a new route /about that returns the message "This is the about page."

Solution:

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

Common Mistakes and Tips

  • Virtual Environment Activation: Ensure your virtual environment is activated before installing Flask or running your application.
  • Indentation Errors: Python is sensitive to indentation. Make sure your code blocks are properly indented.
  • Port Conflicts: If port 5000 is already in use, you can specify a different port by modifying app.run(debug=True, port=5001).

Conclusion

Congratulations! You've created your first Flask application. You now know how to set up a project, create a basic Flask app, and define routes. In the next section, we will dive deeper into Flask's application structure to help you organize your code better.

© Copyright 2024. All rights reserved