Flask Error and Debug Information
Purpose: To learn where to find error and debug information in your Flask application.
When a full-stack web application isn't working as expected and it's your job to fix it, it is tricky but crucial to figure out which part of the stack the error originated in. Your best friends are (1) knowing the order of request and response, and (2) knowing where to find error messages and debug information. In Exercise 1.1, we went over how to find error messages and debug information for HTML, CSS, and Javascript, which run inside the Browser. In this exercise, we will focus on finding error messages and debug information in Flask.
First, Create a Deliberate Error in the Batpage (Flask version)
To test this, start with the Sample Page, then put in a deliberate bug by changing line 12
from
def contact(): return render_template("contact.html")
to:
def contact(): return render_template("contact.html") + bla
Since bla is an undefined variable, this arrangement should trigger an error whenever you go to the contact page. Practice finding the error as follows:
Find the Error in Dev Mode with Debug On
First, run Flask in dev mode with debug on:
python -m flask run --debug
In dev mode, the Flask server usually listens on port 5000. By default, it logs all HTTP requests and errors to the command console. If debug mode is on, it should also log errors to the Browser. Try and see.
Find the Error in Dev Mode with Debug Off
Now, run Flask in dev mode with debug off (omitting --debug):
python -m flask run
In the Browser, Flask simply produces an HTTP 500 error (internal server error). The message is accessible only on the command console. Try and see.
Find the Error on Localhost using XAMPP CGI
Now, run from localhost with the XAMPP Apache server on. Since Flask is running via CGI, the error should be logged to the Apache error log (normally error.log).
Find the Error on Webhost using Phusion Passenger
Before adding the error to your code on the webhost, you can specify a log file for errors. Go to Setup Python App and click "Edit" on your project. In the "Passenger Log File" box, enter the name of your log file. As a suggestion, you may want to put it in your project directory, although you don't have to. A common name for this log is "stderr.log", but you can call it whatever you want.
Now, add the error to your code on the webhost in the project you created in Exercise 2.3 and go to contact.html in the browser to trigger the error.
Remove the Error from Your Code
Once done with this exercise, feel free to remove the error from your code on your localhost and webhost.