InterviewSolution
| 1. |
Describe Blueprint Error Handlers. |
|
Answer» Most error handlers will operate as expected in Modular Applications with Blueprints. There is a caveat, though, when it comes to handlers for 404 and 405 errors. These error handlers are only called when there is an appropriate raise statement or a call to abort in one of the blueprint's view FUNCTIONS; they are not called when there is invalid URL access, for example. Because the blueprint does not own a certain URL SPACE, the application instance has no means of knowing which blueprint error handler to apply if the URL is wrong. If you want to use alternative HANDLING strategies for these errors based on URL prefixes, you can do so using the request PROXY object at the application level. from flask import jsonify, render_template[Text Wrapping Break][Text Wrapping Break]# at the application level[Text Wrapping Break]# not the blueprint level[Text Wrapping Break]@app.errorhandler(404)[Text Wrapping Break]def page_not_found(e):[Text Wrapping Break] # if a request is in our blog URL space[Text Wrapping Break] if request.path.startswith('/blog/'):[Text Wrapping Break] # we return a custom blog 404 page[Text Wrapping Break] return render_template("blog/404.html"), 404[Text Wrapping Break] else:[Text Wrapping Break] # otherwise we return our generic site-wide 404 page[Text Wrapping Break] return render_template("404.html"), 404[Text Wrapping Break][Text Wrapping Break]@app.errorhandler(405)[Text Wrapping Break]def method_not_allowed(e):[Text Wrapping Break] # if a request has the wrong method to our API[Text Wrapping Break] if request.path.startswith('/api/'):[Text Wrapping Break] # we return a json saying so[Text Wrapping Break] return jsonify(message="Method Not Allowed"), 405[Text Wrapping Break] else:[Text Wrapping Break] # otherwise we return a generic site-wide 405 page[Text Wrapping Break] return render_template("405.html"), 405 |
|