Flask provides a built-in debugger when running in development mode. You can enable it by setting:
export FLASK_ENV=development
export FLASK_DEBUG=1
flask run
Or, in your app.py, set:
app = Flask(__name__)
app.config["DEBUG"] = True
Now, Flask will show detailed error messages if something goes wrong.
Instead of printing errors, use logging:
import logging
logging.basicConfig(level=logging.DEBUG)
@app.route("/")
def home():
logging.debug("Home route accessed")
return "Hello, Flask!"
We use unittest (built-in) or pytest (recommended):
pip install pytest
Create test_app.py
:
import pytest
from app import app
@pytest.fixture
def client():
app.config["TESTING"] = True
with app.test_client() as client:
yield client
def test_home_route(client):
response = client.get("/")
assert response.status_code == 200
assert b"Hello" in response.data
Step 5: Run the Tests
pytest test_app.py
Port Already in Use?
lsof -i :5000 # Find the process using port 5000
kill -9 PID # Kill the process
Import Errors?
Ensure your virtual environment is activated:
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
In this guide, we covered:
✅ Enabling Flask Debug Mode for better error handling.
✅ Using logging to track issues.
✅ Writing and running unit tests with pytest.
✅ Fixing common Flask errors.
Now, your Flask app is bug-free and well-tested! 🚀