Lesson 1
Introduction to Flask
Introduction to Flask

Welcome to the first lesson of our course. In this lesson, we will focus on setting up Flask and returning a simple string through a basic route. Flask is a popular, lightweight web framework for Python that is widely used for web development due to its simplicity and flexibility.

What is Flask?

Flask is a micro web framework for Python developed by Armin Ronacher. It is termed as "micro" not because of its capabilities but its minimalistic core, which leaves the organizational structure and choice of libraries up to the developer. This makes Flask an excellent choice for web development, providing the essentials without enforcing dependencies or project layout constraints.

Why Flask for Web Development?

Flask is popular in the web development community for several reasons:

  • Lightweight and Simple: Flask offers the core tools required for building a web application, without the complexity of more heavyweight frameworks.
  • Flexible: It gives you the freedom to structure your web application in the way that best suits your project.
  • Extensible: Flask has a vast ecosystem of extensions that allow you to add functionality such as database integration, form validation, authentication, and more.
Installing Flask

To get started, you need to install Flask. You can do this using pip, which is a package installer for Python.

Open your command prompt or terminal and run the following command:

Plain text
1pip install flask

If you are using the CodeSignal environment, you do not need to worry about this step, as Flask comes pre-installed. However, knowing how to install Flask is essential for your development environment.

Importing and Initializing Flask

Now that we have Flask installed, let's create a basic Flask application. We'll start by creating a file named app.py inside a directory named app.

Python
1# Import the Flask class from the flask package 2from flask import Flask 3 4# Create an instance of the Flask class 5app = Flask(__name__)

Here, we're importing the Flask class, which we will use to create our Flask application. We then create an instance of the Flask class, naming it app. The __name__ variable is passed to the Flask constructor to help it find important files like templates and static files.

Define a Route and View Function

Next, we'll define a route and a view function. A route is a mapping from a URL to a function that returns the content for that URL. Let's create a simple route that returns a welcome message.

Add the following code to app.py:

Python
1# Import the Flask class from the flask package 2from flask import Flask 3 4# Create an instance of the Flask class 5app = Flask(__name__) 6 7# Define a route for the root URL 8@app.route('/') 9# Define a view function associated with the route 10def welcome(): 11 return "Welcome to your Flask App!"

Let's break this down step by step:

  • The @app.route('/') line is a decorator. A decorator is a special type of function in Python that modifies the behavior of another function. In this case, it tells Flask to execute the welcome function whenever someone accesses the root URL ('/') of the web application.
  • The welcome function is the view function associated with the route. It returns the content to be displayed at the root URL – in this case, a simple welcome message.
Running the Flask Application Locally

Finally, let's set up our Flask application to run on a local server. We'll add the following code to app.py:

Python
1# Import the Flask class from the flask package 2from flask import Flask 3 4# Create an instance of the Flask class 5app = Flask(__name__) 6 7# Define a route for the root URL 8@app.route('/') 9# Define a view function associated with the route 10def welcome(): 11 return "Welcome to your Flask App!" 12 13# Check if the script is run directly 14if __name__ == '__main__': 15 # Run the Flask application 16 app.run(host='0.0.0.0', port=3000, debug=True)

In this section, we check if the script is run directly by using the condition if __name__ == '__main__'. This ensures that the Flask application runs only if the script is executed directly, not if it is imported as a module.

The app.run(host='0.0.0.0', port=3000, debug=True) line starts the Flask development server. We set the host to '0.0.0.0' to make the server accessible externally, configure the port to 3000, and enable debug=True to provide helpful error messages and auto-reload the server when code changes.

By breaking down the creation of a basic Flask application into these steps, we've built a simple Flask app that displays a welcome message. Now you can proceed to run your Flask application and see the result.

Starting Your Flask Server

To run your Flask application, navigate to the directory containing app.py and execute the following command in your terminal:

Plain text
1python app.py

Once your server is running, open a web browser and go to http://localhost:3000/. You should see the message "Welcome to your Flask App!"

Understanding the Debug Mode

When you run your Flask application with debug=True, you activate the debug mode. This mode is immensely helpful during development for several reasons, including:

  • Hot Reloading: The server will automatically restart when it detects changes in your code, so you don’t need to stop and start the server manually.
  • Error Messages: A detailed interactive debugger will display useful error messages and stack traces in the web browser and terminal.

The initial logs when you start the server in debug mode might look like this:

Plain text
1 * Serving Flask app 'app' 2 * Debug mode: on 3WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. 4 * Running on all addresses (0.0.0.0) 5 * Running on http://127.0.0.1:3000 6 * Running on http://10.3.76.35:3000 7Press CTRL+C to quit 8 * Restarting with stat 9 * Debugger is active! 10 * Debugger PIN: 144-091-880

Even though debug mode helps in catching errors, some critical errors can still crash the server. In such cases, you might need to restart the server manually.

Summary and Next Steps

In this lesson, you have learned:

  • What Flask is and why it is a popular choice for web development.
  • How to install Flask and verify the installation.
  • How to create a basic Flask application, set up a basic route, and run a Flask server.

Now that you have set up a basic Flask application, you are ready to move on to the practice exercises. These will reinforce what you learned in this lesson and help you gain confidence in using Flask.

As you continue, remember that experimentation is key to learning. Don't be afraid to modify the code and see what changes. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.