Basic Structure of a Flask Application in Flask


Flask is a minimal web framework that allows developers to create web applications with Python. Understanding the basic structure of a Flask application is essential to getting started. This article walks you through creating and understanding a simple Flask application structure.

Step 1: Install Flask

If Flask is not already installed, use pip to install it:

            pip install flask
        

Once installed, you're ready to create your first Flask application.

Step 2: Create the Project Directory

Start by creating a directory for your Flask project. For example:

            mkdir flask_app
            cd flask_app
        

This directory will hold all the files related to your Flask application.

Step 3: Create the Main Application File

Create a Python file named app.py. This file will serve as the entry point for your Flask application. Add the following code:

            from flask import Flask

            app = Flask(__name__)

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

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

Here’s what each part of this code does:

  • from flask import Flask: Imports the Flask class.
  • app = Flask(__name__): Creates an instance of the Flask application.
  • @app.route("/"): Defines the root route ("/") and associates it with the home function.
  • app.run(debug=True): Runs the Flask development server with debugging enabled.

Step 4: Run the Application

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

            python app.py
        

The Flask development server will start, and you'll see output like:

            * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
        

Open your browser and navigate to http://127.0.0.1:5000/ to see the output "Welcome to Flask!"

Step 5: Add More Routes

You can add more routes to handle different parts of your application. For example, update app.py to include an additional route:

            @app.route("/about")
            def about():
                return "This is the About Page!"
        

Now, visiting http://127.0.0.1:5000/about will display "This is the About Page!"

Step 6: Organize Your Code

As your application grows, you can organize your code into multiple files and directories. A common structure might look like this:

            flask_app/
            ├── app.py
            ├── templates/
            │   └── index.html
            ├── static/
            │   └── style.css
        

The templates folder holds HTML files, and the static folder holds static assets like CSS and JavaScript files.

Conclusion

The basic structure of a Flask application is straightforward. By understanding the role of each part, you can create and scale your web applications effectively. Experiment with routes and templates to build dynamic web pages with Flask.





Advertisement