Manually Debugging Common Flask Errors
Tags: beginners, programming, python, flask
Published: 2023-06-11 23:29:56

When it comes to testing and debugging while building Flask applications, there are luckily a ton of tools and frameworks that can be utilized — some are even already built-in! However, as many programmers already know, it can be far too easy to rely solely on these methods, leaving one in the weeds when encountering errors that feel all but impossible to decode. In fact, there are a several reasons why knowing how to debug manually in Flask is not only an important skill but a truly invaluable habit to maintain; here are a few examples:
- It provides developers far more **flexibility and control** over the debugging process. You’re able to zone in more closely on the root cause of the issue and tailor your techniques (i.e. print statements, logs, or breakpoints) to fit the situation and/or your particular goals.
- There are few methods for **deepening your understanding** of your codebase and its execution flow that are more valuable than being able to break down your errors into bite-size pieces and truly unravel the source of the bugs. As irritating as it can be to spend portions of your worktime untangling errors instead of actively building, when you’re finally able to move past the error thrown your way with a more concrete understanding of what led to the error and/or how intimately it affected other portions of your code, your time was still genuinely well spent!
- Because it doesn’t require any additional tools or frameworks and it can, manually debugging is usually **non-invasive**. Further, it can be completely directly within the codebase without the added weight of external dependencies.
- In addition to simply being a good habit, several manual debugging techniques can applied across other projects and frameworks, making it an extremely **portable skill**.
- While the process of debugging can often feel time consuming, manual debugging is exceedingly **quick and simple** — it doesn’t rely on extensive configuration nor setup time for additional debugging tools or libraries. This is particularly beneficial when working on projects requiring a quick turnaround.

Now, there are obviously countless situations in which debugging tools, frameworks, or integrated development environments (IDEs, for short) would be ideal — they can provide advanced features, automated breakpoints, and real-time inspections that can make the debugging process feel simpler and more efficient, especially when dealing with large codebases, so the point of this essay isn’t to devalue common debugging tools and frameworks, simply to emphasize why knowing how to (and frequently practicing) manually debug errors is such an important skill and habit. 

To continue, here are some common Flask errors and how to debug them, step-by-step:

First, here’s a code snippet of a simple Flask application with a single route defined for the root URL `('/')` and the route handler will return a simple greeting:

```
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the home page!'

if __name__ == '__main__':
    app.run(debug=True)
```
Let’s see what happens when we try to expand upon it.

### 404 Not Found

- What it means: The requested route or URL does not exist within the Flask application. See the example below:

```
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the home page!'

@app.route('/about')
def about():
    return 'This is the about page.'

if __name__ == '__main__':
    app.run(debug=True)
```
Notice that we wrote in a new route, `'/about'`, but there is not a corresponding route handler, so if you were to try to access the URL in a tool like cURL or Postman, you’d likely encounter the following console error:

```
404 Not Found: The requested URL was not found on the server. If you entered the URL manually, please check your spelling and try again.
```
- First, review the code and ensure that the correct route has been defined
- Then, check for any typos or syntax errors within the route definition
- Next, verify that the Flask server has been restarted after any code changes have been made
- If confident that the code is correct, double-check the URL to ensure it matches the precise route definition
- If the issue persists, you could add print statements and/or logging message in the route handlers (this will trace the execution flow and ensure that the handler function is being called), like such:

```
@app.route('/about')
def about():
    print('Inside the about route handler')
    return 'This is the about page.'
```
The console output will help you determine if the route handler is being reached or if the issue may lie elsewhere.

Further, you could set the Flask debugger setting to `'debug=True'` and intentionally trigger an exception. For instance, the following line could be added inside the ‘about’ route handler:

```
raise Exception('Testing 404 error handling')
```
### 405 Method Not Allowed

- What it means: The requested HTTP method if not allowed for the specified route in the Flask application

```
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the home page!'

@app.route('/about', methods=['GET'])
def about():
    return 'This is the about page.'

if __name__ == '__main__':
    app.run(debug=True)
```
You’ll notice that the route for the `'/about'` page above, is only configured for ‘GET’ requests within the ‘methods’ parameter. Let’s assume you were trying to make a ‘POST’ request, you’d come up against the following error:

```
405 Method Not Allowed: The method is not allowed for the requested URL.
```
- To troubleshoot, you’d first want to double check that the allowed methods specified within the route decorator’s ‘methods’ parameter are accurate within the code
- Then, double check that the HTTP method used in the cURL or Postman request matches the allowed methods written within the code
    - Likewise, ensure that the code wasn’t intentionally restricted to specific HTTP methods and if it was, that the methods match the intended operation
- If the issue persists, add print statements or logging messages in the route handlers, as specified with the 404 error above:

```
@app.route('/about', methods=['GET'])
def about():
    print('Inside the about route handler')
    return 'This is the about page.'
```
- Additionally, you can inspect the request object (`'request.method'`) within the route handler to verify the actual HTTP method being used.

### 500 Internal Server Error

- What it means: An unhandled exception or error has occurred during the execution of the Flask application

```
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the home page!'

@app.route('/about')
def about():
    # Simulating a server error by accessing an undefined variable
    result = 10 / 0
    return 'This is the about page.'

if __name__ == '__main__':
    app.run(debug=True)
```
Admittedly, the snippet above will automatically induce a server error in the `'/about'` route by dividing a number by zero. However, once again by using cURL or Postman, we’ll try to debug this error, step-by-step:

- First, ensure you’re trying to access the correct route within your HTTP processing tool. If incorrect, you’re likely to encounter the following error, meaning an unhandled exception occurred in the execution process:

```
500 Internal Server Error: Internal Server Error
```
 - The console output should also display a traceback with more detailed information about the error.

```
ZeroDivisionError: division by zero
```
 - This error can be resolved by removing or resolving the problematic line. For this specific case, it can can replaced with a valid calculation or simply removed altogether:

```
This error can be resolved by removing or resolving the problematic line. For this specific case, it can can replaced with a valid calculation or simply removed altogether:
```
- If the traceback doesn’t help you identify the error, consider adding print statements with the handler, as seen in the earlier error examples.
- Finally, restart the Flask server and retry accessing the route-in-question to confirm whether the error has been resolved

Admittedly, we’ve only begun to scratch the surface of errors one could encounter when writing and troubleshooting code in Flask, but I’m hopeful this guide will aid other novice programmers in troubleshooting some the most commonly encountered errors within Flask, as it’s certainly a habit I’ve been trying to better ingrain within my own code-writing.