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
Note
Make sure you have installed all essentials (IDE, Python, Git)
Follow these steps to set up the environment for the exercise:
Create the virtual environment:
python3 -m venv venv
Activate the virtual environment:
source venv/bin/activate
Change the working directory:
cd exercises/python-helloworld
Install dependencies:
pip install -r requirements.txt
Run the application:
python app.py
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.