1. Application Endpoints and Logging

In this exercise, you will use a minimal Flask application that looks like this:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
   return "<p>Hello World!</>"

if __name__ == "__main__":
   app.run(host="0.0.0.0")

Your tasks are to extend application endpoints and implement the logging functionality. If you are not familiar with Flask, start with the Flask Quickstart documentation and watch the Flask CS50 video tutorial at the top of this page.

Preparation

Follow these steps to set up the environment for the exercise:

  1. Create the virtual environment: python3 -m venv venv

  2. Activate the virtual environment: source venv/bin/activate

  3. Change the working directory: cd exercises/python-helloworld

  4. Install dependencies: pip install -r requirements.txt

  5. Run the application: python app.py

  6. Test the application in a web browser at: http://192.168.1.3:5000/

Exercise 1.1 - Extend Application Endpoints

The endpoint of a web application is simply a URL where a web browser can access the application. So, to extend application endpoints, you need to define new URL routes and create view functions to match those routes. For a better understanding, carefully read two sections of the Flask documentation:

Tip

Use @app.route() decorator to bind a view function for the application endpoint.

Extend your Python Flask app with /status and /metrics endpoints, considering the following requirements:

  • Both endpoints must return an status code HTTP 200

  • Both endpoints must return a JSON response e.g. {"user": "admin"}

  • The /status endpoint should return a response similar to this example: result: OK - healthy

  • The /metrics endpoint should return a response similar to this example: data: {UserCount: 140, UserCountActive: 23}

Exercise 1.2 - Implement Application Logging

Flask uses standard Python logging module. Messages about your Flask application are logged with app.logger, which takes the same name as app.name. This logger can also be used to log your own messages [3].

Tip

Configure logging for your application as soon as possible when the program starts.

Add a log collection logic for each endpoint in your Flask application according to the following requirements:

  • Logs should be kept in a separate file named app.log.

  • You need to collect logs at the DEBUG level.

  • Each log must be in the same format and include information about the logging level, actual time, endpoint name, and message.

Additional Resources

  1. Flask Quick Start

  2. Flask URL Route Registrations

  3. Flask Logging Documentaion

  4. Logging Facility for Python

  5. Python Basic Logging Tutorial

  6. Python Logging Cookbook

  7. Python Advanced Logging Tutorial

  8. CS50 2020 - Lecture 9 - Flask

  9. Flask Application Video Tutoral from Tech with Tim

  10. Learn Flask for Python - freeCodeCamp Video Tutorial