API¶
This part of the documentation covers all the interfaces of Flask-Utils
Extension¶
- class flask_utils.extension.FlaskUtils(app: Flask | None = None, register_error_handlers: bool = True)[source]¶
FlaskUtils extension class.
This class currently optionally register the custom error handlers found in
flask_utils.errors. Callinit_app()to configure the extension on an application.- Parameters:
app – Flask application instance.
register_error_handlers – Register the custom error handlers. Default is True.
- Example:
from flask import Flask from flask_utils import FlaskUtils app = Flask(__name__) fu = FlaskUtils(app) # or fu = FlaskUtils() fu.init_app(app)
New in version 0.5.0.
- init_app(app: Flask, register_error_handlers: bool = True)[source]¶
Initialize a Flask application for use with this extension instance. This must be called before any request is handled by the application.
If the app is created with the factory pattern, this should be called after the app is created to configure the extension.
If register_error_handlers is True, the custom error handlers will be registered and can then be used in routes to raise errors.
- Parameters:
app – The Flask application to initialize.
register_error_handlers – Register the custom error handlers. Default is True.
- Example:
from flask import Flask from flask_utils import FlaskUtils app = Flask(__name__) fu = FlaskUtils() fu.init_app(app)
New in version 0.5.0.
Custom exceptions¶
Warning
For any of these errors to work, you need to register the error handlers in your Flask app.
To do this, you can call flask_utils.errors.register_error_handlers() with your Flask app as an argument.
from flask_utils import register_error_handlers
register_error_handlers(app)
- exception flask_utils.errors.BadRequestError(msg: str, solution: str = 'Try again.')[source]¶
This is the BadRequestError exception class.
When raised, it will return a 400 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import BadRequestError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise BadRequestError("This is a bad request error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "BadRequestError", "name": "Bad Request", "message": "This is a bad request error.", "solution": "Try again." }, "code": 400 }
New in version 0.1.0.
- exception flask_utils.errors.ConflictError(msg: str, solution: str = 'Try again.')[source]¶
This is the ConflictError exception class.
When raised, it will return a 409 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import ConflictError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise ConflictError("This is a conflict error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "ConflictError", "name": "Conflict", "message": "This is a conflict error.", "solution": "Try again." }, "code": 409 }
New in version 0.1.0.
- exception flask_utils.errors.FailedDependencyError(msg: str, solution: str = 'Try again later.')[source]¶
This is the FailedDependencyError exception class.
When raised, it will return a 424 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import FailedDependencyError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise FailedDependencyError("This is a failed dependency error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "FailedDependencyError", "name": "Failed Dependency", "message": "This is a failed dependency error.", "solution": "Try again later." }, "code": 424 }
New in version 0.1.0.
- exception flask_utils.errors.ForbiddenError(msg: str, solution: str = 'Try again.')[source]¶
This is the ForbiddenError exception class.
When raised, it will return a 403 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import ForbiddenError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise ForbiddenError("This is a forbidden error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "ForbiddenError", "name": "Forbidden", "message": "This is a forbidden error.", "solution": "Try again." }, "code": 403 }
New in version 0.1.0.
- exception flask_utils.errors.GoneError(msg: str, solution: str = 'Try again later.')[source]¶
This is the GoneError exception class.
When raised, it will return a 410 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import GoneError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise GoneError("This is a gone error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "GoneError", "name": "Ressource is gone.", "message": "This is a gone error.", "solution": "Try again later." }, "code": 410 }
New in version 0.1.0.
- exception flask_utils.errors.NotFoundError(msg: str, solution: str = 'Try again.')[source]¶
This is the NotFoundError exception class.
When raised, it will return 404 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import NotFoundError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise NotFoundError("This is a not found error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "NotFoundError", "name": "Not Found", "message": "This is a not found error.", "solution": "Try again." }, "code": 404 }
New in version 0.1.0.
- exception flask_utils.errors.OriginIsUnreachableError(msg: str, solution: str = 'Try again later.')[source]¶
This is the OriginIsUnreachableError exception class.
When raised, it will return a 523 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import OriginIsUnreachableError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise OriginIsUnreachableError("The origin is unreachable.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "OriginIsUnreachableError", "name": "Origin is unreachable", "message": "The origin is unreachable.", "solution": "Try again later." }, "code": 523 }
New in version 0.1.0.
This is the ServiceUnavailableError exception class.
When raised, it will return a 503 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import ServiceUnavailableError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise ServiceUnavailableError("This is a service unavailable error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "ServiceUnavailableError", "name": "Service Unavailable", "message": "This is a service unavailable error.", "solution": "Try again later." }, "code": 503 }
New in version 0.1.0.
- exception flask_utils.errors.UnauthorizedError(msg: str, solution: str = 'Try again.')[source]¶
This is the UnauthorizedError exception class.
When raised, it will return a 401 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import UnauthorizedError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise UnauthorizedError("This is an unauthorized error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "UnauthorizedError", "name": "Unauthorized", "message": "This is an unauthorized error.", "solution": "Try again." }, "code": 401 }
New in version 0.1.0.
- exception flask_utils.errors.UnprocessableEntityError(msg: str, solution: str = 'Try again.')[source]¶
This is the UnprocessableEntityError exception class.
When raised, it will return a 422 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import UnprocessableEntityError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise UnprocessableEntityError("This is an unprocessable entity error.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "UnprocessableEntityError", "name": "Unprocessable Entity", "message": "This is an unprocessable entity error.", "solution": "Try again." }, "code": 422 }
New in version 0.1.0.
- exception flask_utils.errors.WebServerIsDownError(msg: str, solution: str = 'Try again later.')[source]¶
This is the WebServerIsDownError exception class.
When raised, it will return a 521 status code with the message and solution provided.
- Parameters:
msg – The message to be displayed in the error.
solution – The solution to the error.
- Example:
from flask_utils.errors import WebServerIsDownError # Inside a Flask route @app.route('/example', methods=['POST']) def example_route(): ... if some_condition: raise WebServerIsDownError("The web server is down.")
The above code would return the following JSON response from Flask:
{ "success": false, "error": { "type": "WebServerIsDownError", "name": "Web Server Is Down", "message": "The web server is down.", "solution": "Try again later." }, "code": 521 }
New in version 0.1.0.
Decorators¶
- flask_utils.decorators.validate_params(parameters: Dict[Any, Any], allow_empty: bool = False)[source]¶
Decorator to validate request JSON body parameters.
This decorator ensures that the JSON body of a request matches the specified parameter types and includes all required parameters.
- Parameters:
parameters – Dictionary of parameters to validate. The keys are parameter names and the values are the expected types.
allow_empty – Allow empty values for parameters. Defaults to False.
- Raises:
flask_utils.errors.badrequest.BadRequestError – If the JSON body is malformed, the Content-Type header is missing or incorrect, required parameters are missing, or parameters are of the wrong type.
- Example:
from flask import Flask, request from typing import List, Dict from flask_utils.decorators import validate_params from flask_utils.errors.badrequest import BadRequestError app = Flask(__name__) @app.route("/example", methods=["POST"]) @validate_params( { "name": str, "age": int, "is_student": bool, "courses": List[str], "grades": Dict[str, int], } ) def example(): """ This route expects a JSON body with the following: - name: str - age: int (optional) - is_student: bool - courses: list of str - grades: dict with str keys and int values """ data = request.get_json() return data
Tip
- You can use any of the following types:
str
int
float
bool
List
Dict
Any
Optional
Union
New in version 0.2.0.
Utilities¶
- flask_utils.utils.is_it_true(value: str) bool[source]¶
This function checks if a string value is true. Useful for flask’s request.form.get() method and request.args.get() method
- Parameters:
value – String value to check if it is true
- Returns:
True if value is true, False otherwise
- Example:
from flask_utils import is_it_true @app.route('/example', methods=['GET']) def example(): is_ordered = request.args.get('is_ordered', type=is_it_true, default=False)
This allows your API to accept these kind of requests:
import requests response = requests.get('http://localhost:5000/example?is_ordered=true') print(response.json()) # True response = requests.get('http://localhost:5000/example?is_ordered=1') print(response.json()) # True response = requests.get('http://localhost:5000/example?is_ordered=yes') print(response.json()) # True
New in version 0.4.0.
Private API¶
- flask_utils.decorators._is_optional(type_hint: Type) bool[source]¶
Check if the type hint is
Optional.- Parameters:
type_hint – Type hint to check.
- Returns:
True if the type hint is
Optional, False otherwise.- Example:
from typing import Optional from flask_utils.decorators import _is_optional _is_optional(Optional[str]) # True _is_optional(str) # False
New in version 0.2.0.
- flask_utils.decorators._make_optional(type_hint: Type) Type[source]¶
Wrap type hint with
Optionalif it’s not already.- Parameters:
type_hint – Type hint to wrap.
- Returns:
Type hint wrapped with
Optional.- Example:
from typing import Optional from flask_utils.decorators import _make_optional _make_optional(str) # Optional[str] _make_optional(Optional[str]) # Optional[str]
New in version 0.2.0.
- flask_utils.decorators._is_allow_empty(value: Any, type_hint: Type, allow_empty: bool) bool[source]¶
Determine if the value is considered empty and whether it’s allowed.
- Parameters:
value – Value to check.
type_hint – Type hint to check against.
allow_empty – Whether to allow empty values.
- Returns:
True if the value is empty and allowed, False otherwise.
- Example:
from typing import Optional from flask_utils.decorators import _is_allow_empty _is_allow_empty(None, str, False) # False _is_allow_empty("", str, False) # False _is_allow_empty(None, Optional[str], False) # True _is_allow_empty("", Optional[str], False) # True _is_allow_empty("", Optional[str], True) # True _is_allow_empty("", str, True) # True _is_allow_empty([], Optional[list], False) # True
New in version 0.2.0.
- flask_utils.decorators._check_type(value: Any, expected_type: Type, allow_empty: bool = False, curr_depth: int = 0) bool[source]¶
Check if the value matches the expected type, recursively if necessary.
- Parameters:
value – Value to check.
expected_type – Expected type.
allow_empty – Whether to allow empty values.
curr_depth – Current depth of the recursive check.
- Returns:
True if the value matches the expected type, False otherwise.
- Example:
from typing import List, Dict from flask_utils.decorators import _check_type _check_type("hello", str) # True _check_type(42, int) # True _check_type(42.0, float) # True _check_type(True, bool) # True _check_type(["hello", "world"], List[str]) # True _check_type({"name": "Jules", "city": "Rouen"}, Dict[str, str]) # True
It also works recursively:
from typing import List, Dict from flask_utils.decorators import _check_type _check_type(["hello", "world"], List[str]) # True _check_type(["hello", 42], List[str]) # False _check_type([{"name": "Jules", "city": "Rouen"}, {"name": "John", "city": "Paris"}], List[Dict[str, str]]) # True _check_type([{"name": "Jules", "city": "Rouen"}, {"name": "John", "city": 42}], List[Dict[str, str]]) # False
New in version 0.2.0.
- flask_utils.errors._error_template._generate_error_json(error: _BaseFlaskException, status_code: int) Response[source]¶
This function is used to generate a json of the error passed
- Parameters:
error – The error containing the message and solution
status_code – The status code of the error.
- Returns:
Returns a json containing all the info
- Example:
from flask_utils.errors import _BaseFlaskException from flask_utils.errors._error_template import _generate_error_json class MyError(_BaseFlaskException): self.name = "MyError" self.msg = msg self.solution = solution self.status_code = 666 error = MyError("This is an error", "This is the solution") json = _generate_error_json(error, 666)
New in version 0.1.0.
- flask_utils.errors._register_error_handlers(application: Flask) None[source]¶
This function will register all the error handlers for the application
- Parameters:
application – The Flask application to register the error handlers
- Returns:
None
Changed in version 0.5.0: Made the function private. If you want to register the custom error handlers, you need to pass register_error_handlers=True to the
flask_utils.extension.FlaskUtilsclass or toflask_utils.extension.FlaskUtils.init_app()from flask import Flask from flask_utils import FlaskUtils app = Flask(__name__) utils = FlaskUtils(app) # OR utils = FlaskUtils() utils.init_app(app)
New in version 0.1.0.