dservercore.blueprint

Custom dserver Blueprint

Classes

Blueprint(*args, **kwargs)

Bring together flask-smorest blueprint and custom sort mixin.

class dservercore.blueprint.Blueprint(*args, **kwargs)

Bases: Blueprint, SortMixin

Bring together flask-smorest blueprint and custom sort mixin.

__init__(*args, **kwargs)
ARGUMENTS_PARSER = <webargs.flaskparser.FlaskParser object>
DEFAULT_ALLOWED_SORT_FIELDS = []
DEFAULT_LOCATION_CONTENT_TYPE_MAPPING = {'files': 'multipart/form-data', 'form': 'application/x-www-form-urlencoded', 'json': 'application/json'}
DEFAULT_PAGINATION_PARAMETERS = {'max_page_size': 100, 'page': 1, 'page_size': 10}
DEFAULT_SORT_PARAMETERS = {'sort': []}
DOCSTRING_INFO_DELIMITER = '---'
ETAG_INCLUDE_HEADERS = ['X-Pagination']
HTTP_METHODS = ['OPTIONS', 'HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE']
METHODS_ALLOWING_SET_ETAG = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH']
METHODS_CHECKING_NOT_MODIFIED = ['GET', 'HEAD']
METHODS_NEEDING_CHECK_ETAG = ['PUT', 'PATCH', 'DELETE']
PAGINATION_ARGUMENTS_PARSER = <webargs.flaskparser.FlaskParser object>
PAGINATION_HEADER_NAME = 'X-Pagination'
SORT_ARGUMENTS_PARSER = <dservercore.sort.CommaSeparatedListFlaskParser object>
SORT_HEADER_NAME = 'X-Sort'
add_app_template_filter(f: Callable[[...], Any], name: str | None = None) None

Register a template filter, available in any template rendered by the application. Works like the app_template_filter() decorator. Equivalent to Flask.add_template_filter().

Parameters:

name – the optional name of the filter, otherwise the function name will be used.

add_app_template_global(f: Callable[[...], Any], name: str | None = None) None

Register a template global, available in any template rendered by the application. Works like the app_template_global() decorator. Equivalent to Flask.add_template_global().

Added in version 0.10.

Parameters:

name – the optional name of the global, otherwise the function name will be used.

add_app_template_test(f: Callable[[...], bool], name: str | None = None) None

Register a template test, available in any template rendered by the application. Works like the app_template_test() decorator. Equivalent to Flask.add_template_test().

Added in version 0.10.

Parameters:

name – the optional name of the test, otherwise the function name will be used.

add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, *, parameters=None, tags=None, **options)

Register url rule in application

Also stores doc info for later registration

Use this to register a MethodView or a resource function.

Parameters:
  • rule (str) – URL rule as string.

  • endpoint (str) – Endpoint for the registered URL rule (defaults to function name).

  • view_func (callable|MethodView) – View function or MethodView class

  • parameters (list) – List of parameter descriptions relevant to all operations in this path. Only used to document the resource.

  • tags (list) – List of tags for the resource. If None, Blueprint name is used.

  • options – Options to be forwarded to the underlying werkzeug.routing.Rule object.

after_app_request(f: T_after_request) T_after_request

Like after_request(), but after every request, not only those handled by the blueprint. Equivalent to Flask.after_request().

after_request(f: T_after_request) T_after_request

Register a function to run after each request to this object.

The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.

If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that.

This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use Blueprint.after_app_request().

alt_response(status_code, response=None, *, schema=None, content_type=None, description=None, example=None, examples=None, headers=None, success=False)

Decorator documenting an alternative response

Parameters:
  • status_code (int|str|HTTPStatus) – HTTP status code.

  • response (str) – Response reference.

  • schema|str|dict (schema) – Schema class or instance or reference or dict.

  • description (str) – Description of the response (default: None).

  • example (dict) – Example of response message.

  • examples (dict) – Examples of response message.

  • headers (dict) – Headers returned by the response.

  • success (bool) – True if this response is part of the normal flow of the function. Default: False.

This decorator allows the user to document an alternative response. This can be an error managed with abort or any response that is not the primary flow of the function documented by Blueprint.response.

When a response reference is passed as response, it is used as description and the keyword arguments are ignored. Otherwise, a description is built from the keyword arguments.

See document-alternative-responses.

app_context_processor(f: T_template_context_processor) T_template_context_processor

Like context_processor(), but for templates rendered by every view, not only by the blueprint. Equivalent to Flask.context_processor().

app_errorhandler(code: type[Exception] | int) Callable[[T_error_handler], T_error_handler]

Like errorhandler(), but for every request, not only those handled by the blueprint. Equivalent to Flask.errorhandler().

app_template_filter(name: str | None = None) Callable[[T_template_filter], T_template_filter]

Register a template filter, available in any template rendered by the application. Equivalent to Flask.template_filter().

Parameters:

name – the optional name of the filter, otherwise the function name will be used.

app_template_global(name: str | None = None) Callable[[T_template_global], T_template_global]

Register a template global, available in any template rendered by the application. Equivalent to Flask.template_global().

Added in version 0.10.

Parameters:

name – the optional name of the global, otherwise the function name will be used.

app_template_test(name: str | None = None) Callable[[T_template_test], T_template_test]

Register a template test, available in any template rendered by the application. Equivalent to Flask.template_test().

Added in version 0.10.

Parameters:

name – the optional name of the test, otherwise the function name will be used.

app_url_defaults(f: T_url_defaults) T_url_defaults

Like url_defaults(), but for every request, not only those handled by the blueprint. Equivalent to Flask.url_defaults().

app_url_value_preprocessor(f: T_url_value_preprocessor) T_url_value_preprocessor

Like url_value_preprocessor(), but for every request, not only those handled by the blueprint. Equivalent to Flask.url_value_preprocessor().

arguments(schema, *, location='json', content_type=None, required=True, description=None, example=None, examples=None, **kwargs)

Decorator specifying the schema used to deserialize parameters

Parameters:
  • schema (type|Schema) – Marshmallow Schema class or instance used to deserialize and validate the argument.

  • location (str) – Location of the argument.

  • content_type (str) – Content type of the argument. Should only be used in conjunction with json, form or files location. The default value depends on the location and is set in Blueprint.DEFAULT_LOCATION_CONTENT_TYPE_MAPPING. This is only used for documentation purpose.

  • required (bool) – Whether argument is required (default: True).

  • description (str) – Argument description.

  • example (dict) – Parameter example.

  • examples (dict) – Parameter examples.

  • kwargs – Keyword arguments passed to the webargs use_args decorator used internally.

The required and description only affect body arguments (OpenAPI 2) or requestBody (OpenAPI 3), because the docs expose the whole schema. For other locations, the schema is turned into an array of parameters and the required/description value of each parameter item is taken from the corresponding field in the schema.

The example and examples parameters are mutually exclusive and should only be used with OpenAPI 3 and when location is json.

See Arguments.

before_app_request(f: T_before_request) T_before_request

Like before_request(), but before every request, not only those handled by the blueprint. Equivalent to Flask.before_request().

before_request(f: T_before_request) T_before_request

Register a function to run before each request.

For example, this can be used to open a database connection, or to load the logged in user from the session.

@app.before_request
def load_user():
    if "user_id" in session:
        g.user = db.session.get(session["user_id"])

The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.

This is available on both app and blueprint objects. When used on an app, this executes before every request. When used on a blueprint, this executes before every request that the blueprint handles. To register with a blueprint and execute before every request, use Blueprint.before_app_request().

check_etag(etag_data, etag_schema=None)

Compare If-Match header with computed ETag

Raise 412 if If-Match header does not match.

Must be called from resource code to check ETag.

Unfortunately, there is no way to call it automatically. It is the developer’s responsability to do it. However, a warning is issued at runtime if this function was not called.

Issues a warning if called in a method other than PUT, PATCH, or DELETE.

context_processor(f: T_template_context_processor) T_template_context_processor

Registers a template context processor function. These functions run before rendering a template. The keys of the returned dict are added as variables available in the template.

This is available on both app and blueprint objects. When used on an app, this is called for every rendered template. When used on a blueprint, this is called for templates rendered from the blueprint’s views. To register with a blueprint and affect every template, use Blueprint.app_context_processor().

delete(rule: str, **options: Any) Callable[[T_route], T_route]

Shortcut for route() with methods=["DELETE"].

Added in version 2.0.

static doc(**kwargs)

Decorator adding description attributes to a view function

Values passed as kwargs are copied verbatim in the docs

Example:

@blp.doc(description="Return pets based on ID",
         summary="Find pets by ID"
)
def get(...):
    ...
endpoint(endpoint: str) Callable[[F], F]

Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule().

app.add_url_rule("/ex", endpoint="example")

@app.endpoint("example")
def example():
    ...
Parameters:

endpoint – The endpoint name to associate with the view function.

errorhandler(code_or_exception: type[Exception] | int) Callable[[T_error_handler], T_error_handler]

Register a function to handle errors by code or exception class.

A decorator that is used to register a function given an error code. Example:

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

You can also register handlers for arbitrary exceptions:

@app.errorhandler(DatabaseError)
def special_exception_handler(error):
    return 'Database connection failed', 500

This is available on both app and blueprint objects. When used on an app, this can handle errors from every request. When used on a blueprint, this can handle errors from requests that the blueprint handles. To register with a blueprint and affect every request, use Blueprint.app_errorhandler().

Added in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers.

Added in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class.

Parameters:

code_or_exception – the code as integer for the handler, or an arbitrary exception

etag(obj)

Decorator adding ETag management to the endpoint

The etag decorator expects the decorated view function to return a Response object. It is the case if it is decorated with the response decorator.

The etag decorator may be used to decorate a MethodView. In this case, it applies to all HTTP methods in the MethodView.

See ETag.

get(rule: str, **options: Any) Callable[[T_route], T_route]

Shortcut for route() with methods=["GET"].

Added in version 2.0.

get_send_file_max_age(filename: str | None) int | None

Used by send_file() to determine the max_age cache value for a given file path if it wasn’t passed.

By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable.

Changed in version 2.0: The default configuration is None instead of 12 hours.

Added in version 0.9.

property has_static_folder: bool

True if static_folder is set.

Added in version 0.5.

property jinja_loader: FileSystemLoader | None

The Jinja loader for this object’s templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set.

Added in version 0.5.

make_setup_state(app: Flask, options: dict, first_registration: bool = False) BlueprintSetupState

Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state.

open_resource(resource: str, mode: str = 'rb') IO

Open a resource file relative to root_path for reading.

For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with:

with app.open_resource("schema.sql") as f:
    conn.executescript(f.read())
Parameters:
  • resource – Path to the resource relative to root_path.

  • mode – Open the file in this mode. Only reading is supported, valid values are “r” (or “rt”) and “rb”.

paginate(pager=None, *, page=None, page_size=None, max_page_size=None)

Decorator adding pagination to the endpoint

Parameters:
  • pager (Page) – Page class used to paginate response data

  • page (int) – Default requested page number (default: 1)

  • page_size (int) – Default requested page size (default: 10)

  • max_page_size (int) – Maximum page size (default: 100)

If a Page class is provided, it is used to paginate the data returned by the view function, typically a lazy database cursor.

Otherwise, pagination is handled in the view function.

The decorated function may return a tuple including status and/or headers, like a typical flask view function. It may not return a Response object.

See Pagination.

patch(rule: str, **options: Any) Callable[[T_route], T_route]

Shortcut for route() with methods=["PATCH"].

Added in version 2.0.

post(rule: str, **options: Any) Callable[[T_route], T_route]

Shortcut for route() with methods=["POST"].

Added in version 2.0.

put(rule: str, **options: Any) Callable[[T_route], T_route]

Shortcut for route() with methods=["PUT"].

Added in version 2.0.

record(func: Callable) None

Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the make_setup_state() method.

record_once(func: Callable) None

Works like record() but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called.

register(app: Flask, options: dict) None

Called by Flask.register_blueprint() to register all views and callbacks registered on the blueprint with the application. Creates a BlueprintSetupState and calls each record() callback with it.

Parameters:
  • app – The application this blueprint is being registered with.

  • options – Keyword arguments forwarded from register_blueprint().

Changed in version 2.3: Nested blueprints now correctly apply subdomains.

Changed in version 2.1: Registering the same blueprint with the same name multiple times is an error.

Changed in version 2.0.1: Nested blueprints are registered with their dotted name. This allows different blueprints with the same name to be nested at different locations.

Changed in version 2.0.1: The name option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for url_for.

register_blueprint(blueprint, **options)

Register a nested blueprint in application

Also stores doc info from the nested bluepint for later registration.

Use this to register a nested Blueprint.

Parameters:
  • blueprint (Blueprint) – Blueprint to register under this blueprint.

  • options – Options to be forwarded to the underlying flask.Blueprint.register_blueprint() method.

See register-nested-blueprints.

register_error_handler(code_or_exception: type[Exception] | int, f: ft.ErrorHandlerCallable) None

Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage.

Added in version 0.7.

register_views_in_doc(api, app, spec, *, name, parameters)

Register views information in documentation

If a schema in a parameter or a response appears in the spec schemas section, it is replaced by a reference in the parameter or response documentation:

“schema”:{“$ref”: “#/components/schemas/MySchema”}

response(status_code, schema=None, *, content_type=None, description=None, example=None, examples=None, headers=None)

Decorator generating an endpoint response

Parameters:
  • status_code (int|str|HTTPStatus) – HTTP status code. Used if none is returned from the view function.

  • schema|str|dict (schema) – Schema class or instance or reference or dict. If not None, will be used to serialize response data.

  • content_type (str) – Content type of the response.

  • description (str) – Description of the response (default: None).

  • example (dict) – Example of response message.

  • examples (dict) – Examples of response message.

  • headers (dict) – Headers returned by the response.

The decorated function is expected to return the same types of value than a typical flask view function, except the body part may be an object or a list of objects to serialize with the schema, rather than a string.

If the decorated function returns a Response object, the schema and status_code parameters are only used to document the resource. Only in this case, schema may be a reference as string or a schema definition as dict.

The example and examples parameters are mutually exclusive. The latter should only be used with OpenAPI 3.

The example, examples and headers parameters are only used to document the resource.

See Response.

route(rule, *, parameters=None, tags=None, **options)

Decorator to register view function in application and documentation

Calls add_url_rule.

send_static_file(filename: str) Response

The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set.

Added in version 0.5.

set_etag(etag_data, etag_schema=None)

Set ETag for this response

Raise 304 if ETag identical to If-None-Match header

Must be called from resource code, unless the view function is decorated with the response decorator, in which case the ETag is computed by default from response data if set_etag is not called.

Issues a warning if called in a method other than GET, HEAD, POST, PUT or PATCH.

sort(*, sort=None, allowed_sort_fields=None)

Decorator adding sorting to the endpoint

Parameters:
  • sort (str) – Default requested sort string

  • allowed_sort_fields (list of str) – Allowed sort fields

The decorated function may return a tuple including status and/or headers, like a typical flask view function. It may not return a Response object.

property static_folder: str | None

The absolute path to the configured static folder. None if no static folder is set.

property static_url_path: str | None

The URL prefix that the static route will be accessible from.

If it was not configured during init, it is derived from static_folder.

teardown_app_request(f: T_teardown) T_teardown

Like teardown_request(), but after every request, not only those handled by the blueprint. Equivalent to Flask.teardown_request().

teardown_request(f: T_teardown) T_teardown

Register a function to be called when the request context is popped. Typically this happens at the end of each request, but contexts may be pushed manually as well during testing.

with app.test_request_context():
    ...

When the with block exits (or ctx.pop() is called), the teardown functions are called just before the request context is made inactive.

When a teardown function was called because of an unhandled exception it will be passed an error object. If an errorhandler() is registered, it will handle the exception and the teardown will not receive it.

Teardown functions must avoid raising exceptions. If they execute code that might fail they must surround that code with a try/except block and log any errors.

The return values of teardown functions are ignored.

This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use Blueprint.teardown_app_request().

url_defaults(f: T_url_defaults) T_url_defaults

Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.

This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use Blueprint.app_url_defaults().

url_value_preprocessor(f: T_url_value_preprocessor) T_url_value_preprocessor

Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions.

The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view.

The function is passed the endpoint name and values dict. The return value is ignored.

This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use Blueprint.app_url_value_preprocessor().

name: str
import_name

The name of the package or module that this object belongs to. Do not change this once it is set by the constructor.

template_folder

The path to the templates folder, relative to root_path, to add to the template loader. None if templates should not be added.

root_path

Absolute path to the package on the filesystem. Used to look up resources contained in the package.

cli

The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered.

view_functions: dict[str, t.Callable]

A dictionary mapping endpoint names to view functions.

To register a view function, use the route() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.

error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]]

A data structure of registered error handlers, in the format {scope: {code: {class: handler}}}. The scope key is the name of a blueprint the handlers are active for, or None for all requests. The code key is the HTTP status code for HTTPException, or None for other exceptions. The innermost dictionary maps exception classes to handler functions.

To register an error handler, use the errorhandler() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.

before_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]]

A data structure of functions to call at the beginning of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.

To register a function, use the before_request() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.

after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable]]

A data structure of functions to call at the end of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.

To register a function, use the after_request() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.

teardown_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.TeardownCallable]]

A data structure of functions to call at the end of each request even if an exception is raised, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.

To register a function, use the teardown_request() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.

template_context_processors: dict[ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]]

A data structure of functions to call to pass extra context values when rendering templates, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.

To register a function, use the context_processor() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.

url_value_preprocessors: dict[ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable]]

A data structure of functions to call to modify the keyword arguments passed to the view function, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.

To register a function, use the url_value_preprocessor() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.

url_default_functions: dict[ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]]

A data structure of functions to call to modify the keyword arguments when generating URLs, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.

To register a function, use the url_defaults() decorator.

This data structure is internal. It should not be modified directly and its format may change at any time.