miguelgrinberg / flasky

Companion code to my O'Reilly book "Flask Web Development", second edition.
MIT License
8.54k stars 4.21k forks source link

Example 14-4 Question in 2nd Edition #556

Closed samuelerickson977 closed 1 year ago

samuelerickson977 commented 1 year ago

Why doesn't page_not_found use @api_blueprint.app_errorhandler(404) instead of @main.app_errorhandler(404)?

miguelgrinberg commented 1 year ago

Because the 404 handler needs to serve both the regular web clients and the api clients. The handler in he main blueprint uses content negotiation headers to serve te correct response to each client.

samuelerickson977 commented 1 year ago

I see where I was confused. In the book, the Example 14-4 says that this code is in app/api/errors.py, but really this code is in app/main/errors.py. So basically, even though the error handler is technically in a different blueprint than api, it will still get called? Is this the best way to do this?

miguelgrinberg commented 1 year ago

The error handler function is decorated with app_errorhandler. This means that this is an app-wide error handler. If you had used errorhandler instead, then it would be limited to the blueprint in which it is defined.

In my experience, using blueprint specific error handlers is more complicated. The 404 example is actually a very good one. How would Flask know which blueprint a not found endpoint belongs to? By definition an unknown URL does not belong to any blueprint, so it cannot select a blueprint-specific error handler to use and will only invoke an app-wide error handler.

samuelerickson977 commented 1 year ago

Thank you, now I do remember when you discussed that in the book.