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 venvActivate the virtual environment:
source venv/bin/activateChange the working directory:
cd exercises/python-helloworldInstall dependencies:
pip install -r requirements.txtRun the application:
python app.pyTest 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 200Both endpoints must return a JSON response e.g.
{"user": "admin"}The
/statusendpoint should return a response similar to this example:result: OK - healthyThe
/metricsendpoint 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
DEBUGlevel.Each log must be in the same format and include information about the logging level, actual time, endpoint name, and message.