Registering a blueprint 

A Flask application must have the blueprints registered. In some cases, there will be multiple instances of a blueprint, each at a different point in the URI path. In our case, we only have a single instance of the blueprint at the root of the URI path.

In the preceding examples, the bad request data was signaled by raising a BadRequest exception. A Flask error handler can be defined to transform an exception object to a standardized RESTful response document in JSON format.

The example Flask application is shown here:

class BadRequest(Exception):
pass

def make_app() -> Flask:

app = Flask(__name__)

@app.errorhandler(BadRequest)
def error_message(ex) -> Tuple[Dict[str, Any], HTTPStatus]:
current_app.logger.error(f"{ex.args}")
return jsonify(status="Bad Request", message=ex.args), HTTPStatus.BAD_REQUEST

app.register_blueprint(rolls)

return app

The function name, make_app(), is expected by Flask. Using this standard name makes it easy to launch the application. It also makes it easier to integrate with products such as uWSGI or Gunicorn.

Once the Flask object, app, is created, the @app.errorhandler decorator can be used to map Python exceptions to generic responses. This technique will replace Flask's default HTML-based responses with JSON-based responses. The advantage of JSON-format responses is that they make the RESTful API provide more consistent behavior.

The rolls blueprint, defined in previous examples, is registered at the root of the URI path. This make_app() function can also be used to include configuration parameters. It's also common to see a sequence of extension.init_app(app) function calls for any of the Flask extensions being used.

Let's look at how we can create a secure REST service in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset