class documentation

Common behavior shared between :class:`~flask.Flask` and :class:`~flask.blueprints.Blueprint`. :param import_name: The import name of the module where this object is defined. Usually :attr:`__name__` should be used. :param static_folder: Path to a folder of static files to serve. If this is set, a static route will be added. :param static_url_path: URL prefix for the static route. :param template_folder: Path to a folder containing template files. for rendering. If this is set, a Jinja loader will be added. :param root_path: The path that static, template, and resource files are relative to. Typically not set, it is discovered based on the ``import_name``. .. versionadded:: 2.0

Method __init__ Undocumented
Method __repr__ Undocumented
Method add_url_rule Register a rule for routing incoming requests and building URLs. The :meth:`route` decorator is a shortcut to call this with the ``view_func`` argument. These are equivalent:
Method after_request Register a function to run after each request to this object.
Method before_request Register a function to run before each request.
Method 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.
Method delete Shortcut for :meth:`route` with ``methods=["DELETE"]``.
Method endpoint Decorate a view function to register it for the given endpoint. Used if a rule is added without a ``view_func`` with :meth:`add_url_rule`.
Method errorhandler Register a function to handle errors by code or exception class.
Method get Shortcut for :meth:`route` with ``methods=["GET"]``.
Method get_send_file_max_age Used by :func:`send_file` to determine the ``max_age`` cache value for a given file path if it wasn't passed.
Method open_resource Open a resource file relative to :attr:`root_path` for reading.
Method patch Shortcut for :meth:`route` with ``methods=["PATCH"]``.
Method post Shortcut for :meth:`route` with ``methods=["POST"]``.
Method put Shortcut for :meth:`route` with ``methods=["PUT"]``.
Method register_error_handler Alternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage.
Method route Decorate a view function to register it with the given URL rule and options. Calls :meth:`add_url_rule`, which has more details about the implementation.
Method send_static_file The view function used to serve files from :attr:`static_folder`. A route is automatically registered for this view at :attr:`static_url_path` if :attr:`static_folder` is set.
Method static_folder.setter Undocumented
Method static_url_path.setter Undocumented
Method teardown_request 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.
Method 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.
Method url_value_preprocessor Register a URL value preprocessor function for all view functions in the application. These functions will be called before the :meth:`before_request` functions.
Class Variable json_decoder Undocumented
Class Variable json_encoder Undocumented
Class Variable name Undocumented
Instance Variable after_request_funcs Undocumented
Instance Variable before_request_funcs Undocumented
Instance Variable cli Undocumented
Instance Variable error_handler_spec Undocumented
Instance Variable import_name Undocumented
Instance Variable root_path Undocumented
Instance Variable teardown_request_funcs Undocumented
Instance Variable template_context_processors Undocumented
Instance Variable template_folder Undocumented
Instance Variable url_default_functions Undocumented
Instance Variable url_value_preprocessors Undocumented
Instance Variable view_functions Undocumented
Property has_static_folder ``True`` if :attr:`static_folder` is set.
Property jinja_loader The Jinja loader for this object's templates. By default this is a class :class:`jinja2.loaders.FileSystemLoader` to :attr:`template_folder` if it is set.
Property static_folder The absolute path to the configured static folder. ``None`` if no static folder is set.
Property static_url_path The URL prefix that the static route will be accessible from.
Static Method _get_exc_class_and_code Get the exception class being handled. For HTTP status codes or ``HTTPException`` subclasses, return both the exception and status code.
Method _check_setup_finished Undocumented
Method _method_route Undocumented
Instance Variable _static_folder Undocumented
Instance Variable _static_url_path Undocumented
def __init__(self, import_name: str, static_folder: t.Optional[t.Union[str, os.PathLike]] = None, static_url_path: t.Optional[str] = None, template_folder: t.Optional[t.Union[str, os.PathLike]] = None, root_path: t.Optional[str] = None): (source)

Undocumented

def __repr__(self) -> str: (source)

Undocumented

@setupmethod
def add_url_rule(self, rule: str, endpoint: t.Optional[str] = None, view_func: t.Optional[ft.RouteCallable] = None, provide_automatic_options: t.Optional[bool] = None, **options: t.Any): (source)

Register a rule for routing incoming requests and building URLs. The :meth:`route` decorator is a shortcut to call this with the ``view_func`` argument. These are equivalent: .. code-block:: python @app.route("/") def index(): ... .. code-block:: python def index(): ... app.add_url_rule("/", view_func=index) See :ref:`url-route-registrations`. The endpoint name for the route defaults to the name of the view function if the ``endpoint`` parameter isn't passed. An error will be raised if a function has already been registered for the endpoint. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is always added automatically, and ``OPTIONS`` is added automatically by default. ``view_func`` does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the :meth:`endpoint` decorator. .. code-block:: python app.add_url_rule("/", endpoint="index") @app.endpoint("index") def index(): ... If ``view_func`` has a ``required_methods`` attribute, those methods are added to the passed and automatic methods. If it has a ``provide_automatic_methods`` attribute, it is used as the default if the parameter is not passed. :param rule: The URL rule string. :param endpoint: The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to ``view_func.__name__``. :param view_func: The view function to associate with the endpoint name. :param provide_automatic_options: Add the ``OPTIONS`` method and respond to ``OPTIONS`` requests automatically. :param options: Extra options passed to the :class:`~werkzeug.routing.Rule` object.

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 :meth:`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 :meth:`.Blueprint.after_app_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. .. code-block:: python @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 :meth:`.Blueprint.before_app_request`.

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 :meth:`.Blueprint.app_context_processor`.

@setupmethod
def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: (source)

Shortcut for :meth:`route` with ``methods=["DELETE"]``. .. versionadded:: 2.0

@setupmethod
def endpoint(self, endpoint: str) -> t.Callable[[F], F]: (source)

Decorate a view function to register it for the given endpoint. Used if a rule is added without a ``view_func`` with :meth:`add_url_rule`. .. code-block:: python app.add_url_rule("/ex", endpoint="example") @app.endpoint("example") def example(): ... :param endpoint: The endpoint name to associate with the view function.

@setupmethod
def errorhandler(self, code_or_exception: t.Union[t.Type[Exception], int]) -> t.Callable[[T_error_handler], T_error_handler]: (source)

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 :meth:`.Blueprint.app_errorhandler`. .. versionadded:: 0.7 Use :meth:`register_error_handler` instead of modifying :attr:`error_handler_spec` directly, for application wide error handlers. .. versionadded:: 0.7 One can now additionally also register custom exception types that do not necessarily have to be a subclass of the :class:`~werkzeug.exceptions.HTTPException` class. :param code_or_exception: the code as integer for the handler, or an arbitrary exception

@setupmethod
def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: (source)

Shortcut for :meth:`route` with ``methods=["GET"]``. .. versionadded:: 2.0

def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]: (source)

Used by :func:`send_file` to determine the ``max_age`` cache value for a given file path if it wasn't passed. By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from the configuration of :data:`~flask.current_app`. This defaults to ``None``, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable. .. versionchanged:: 2.0 The default configuration is ``None`` instead of 12 hours. .. versionadded:: 0.9

def open_resource(self, resource: str, mode: str = 'rb') -> t.IO[t.AnyStr]: (source)

Open a resource file relative to :attr:`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: .. code-block:: python with app.open_resource("schema.sql") as f: conn.executescript(f.read()) :param resource: Path to the resource relative to :attr:`root_path`. :param mode: Open the file in this mode. Only reading is supported, valid values are "r" (or "rt") and "rb".

@setupmethod
def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: (source)

Shortcut for :meth:`route` with ``methods=["PATCH"]``. .. versionadded:: 2.0

@setupmethod
def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: (source)

Shortcut for :meth:`route` with ``methods=["POST"]``. .. versionadded:: 2.0

@setupmethod
def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: (source)

Shortcut for :meth:`route` with ``methods=["PUT"]``. .. versionadded:: 2.0

@setupmethod
def register_error_handler(self, code_or_exception: t.Union[t.Type[Exception], int], f: ft.ErrorHandlerCallable): (source)

Alternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage. .. versionadded:: 0.7

@setupmethod
def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: (source)

Decorate a view function to register it with the given URL rule and options. Calls :meth:`add_url_rule`, which has more details about the implementation. .. code-block:: python @app.route("/") def index(): return "Hello, World!" See :ref:`url-route-registrations`. The endpoint name for the route defaults to the name of the view function if the ``endpoint`` parameter isn't passed. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and ``OPTIONS`` are added automatically. :param rule: The URL rule string. :param options: Extra options passed to the :class:`~werkzeug.routing.Rule` object.

def send_static_file(self, filename: str) -> Response: (source)

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

Undocumented

@static_url_path.setter
def static_url_path(self, value: t.Optional[str]): (source)

Undocumented

@setupmethod
def teardown_request(self, f: T_teardown) -> T_teardown: (source)

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. .. code-block:: python 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 :meth:`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 :meth:`.Blueprint.teardown_app_request`.

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 :meth:`.Blueprint.app_url_defaults`.

Register a URL value preprocessor function for all view functions in the application. These functions will be called before the :meth:`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 :meth:`.Blueprint.app_url_value_preprocessor`.

Undocumented

import_name = (source)

Undocumented

root_path = (source)

Undocumented

template_folder = (source)

Undocumented

view_functions: t.Dict[str, t.Callable] = (source)

Undocumented

@property
has_static_folder: bool = (source)

``True`` if :attr:`static_folder` is set. .. versionadded:: 0.5

@locked_cached_property
jinja_loader: t.Optional[FileSystemLoader] = (source)

The Jinja loader for this object's templates. By default this is a class :class:`jinja2.loaders.FileSystemLoader` to :attr:`template_folder` if it is set. .. versionadded:: 0.5

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

The URL prefix that the static route will be accessible from. If it was not configured during init, it is derived from :attr:`static_folder`.

@staticmethod
def _get_exc_class_and_code(exc_class_or_code: t.Union[t.Type[Exception], int]) -> t.Tuple[t.Type[Exception], t.Optional[int]]: (source)

Get the exception class being handled. For HTTP status codes or ``HTTPException`` subclasses, return both the exception and status code. :param exc_class_or_code: Any exception class, or an HTTP status code as an integer.

def _check_setup_finished(self, f_name: str): (source)

Undocumented

def _method_route(self, method: str, rule: str, options: dict) -> t.Callable[[T_route], T_route]: (source)

Undocumented

_static_folder = (source)

Undocumented

_static_url_path = (source)

Undocumented