flask API Reference
Full documentation for flask (3.1.3)
flask.Blueprint
Python Library Documentation: class Blueprint in module flask.blueprints
class Blueprint(flask.sansio.blueprints.Blueprint)
| Blueprint(name: 'str', import_name: 'str', static_folder: 'str | os.PathLike[str] | None' = None, static_url_path: 'str | None' = None, template_folder: 'str | os.PathLike[str] | None' = None, url_prefix: 'str | None' = None, subdomain: 'str | None' = None, url_defaults: 'dict[str, t.Any] | None' = None, root_path: 'str | None' = None, cli_group: 'str | None' = <object object at 0x00000232059594F0>) -> 'None'
|
| Method resolution order:
| Blueprint
| flask.sansio.blueprints.Blueprint
| flask.sansio.scaffold.Scaffold
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', import_name: 'str', static_folder: 'str | os.PathLike[str] | None' = None, static_url_path: 'str | None' = None, template_folder: 'str | os.PathLike[str] | None' = None, url_prefix: 'str | None' = None, subdomain: 'str | None' = None, url_defaults: 'dict[str, t.Any] | None' = None, root_path: 'str | None' = None, cli_group: 'str | None' = <object object at 0x00000232059594F0>) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| get_send_file_max_age(self, filename: 'str | None') -> 'int | None'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionchanged:: 2.0
| The default configuration is ``None`` instead of 12 hours.
|
| .. versionadded:: 0.9
|
| open_resource(self, resource: 'str', mode: 'str' = 'rb', encoding: 'str | None' = 'utf-8') -> 't.IO[t.AnyStr]'
| Open a resource file relative to :attr:`root_path` for reading. The
| blueprint-relative equivalent of the app's :meth:`~.Flask.open_resource`
| method.
|
| :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"``.
| :param encoding: Open the file with this encoding when opening in text
| mode. This is ignored when opening in binary mode.
|
| .. versionchanged:: 3.1
| Added the ``encoding`` parameter.
|
| send_static_file(self, filename: 'str') -> 'Response'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.blueprints.Blueprint:
|
| add_app_template_filter(self, f: 'ft.TemplateFilterCallable', name: 'str | None' = None) -> 'None'
| Register a template filter, available in any template rendered by the
| application. Works like the :meth:`app_template_filter` decorator. Equivalent to
| :meth:`.Flask.add_template_filter`.
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| add_app_template_global(self, f: 'ft.TemplateGlobalCallable', name: 'str | None' = None) -> 'None'
| Register a template global, available in any template rendered by the
| application. Works like the :meth:`app_template_global` decorator. Equivalent to
| :meth:`.Flask.add_template_global`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global, otherwise the
| function name will be used.
|
| add_app_template_test(self, f: 'ft.TemplateTestCallable', name: 'str | None' = None) -> 'None'
| Register a template test, available in any template rendered by the
| application. Works like the :meth:`app_template_test` decorator. Equivalent to
| :meth:`.Flask.add_template_test`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| add_url_rule(self, rule: 'str', endpoint: 'str | None' = None, view_func: 'ft.RouteCallable | None' = None, provide_automatic_options: 'bool | None' = None, **options: 't.Any') -> 'None'
| Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for
| full documentation.
|
| The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,
| used with :func:`url_for`, is prefixed with the blueprint's name.
|
| after_app_request(self, f: 'T_after_request') -> 'T_after_request'
| Like :meth:`after_request`, but after every request, not only those handled
| by the blueprint. Equivalent to :meth:`.Flask.after_request`.
|
| app_context_processor(self, f: 'T_template_context_processor') -> 'T_template_context_processor'
| Like :meth:`context_processor`, but for templates rendered by every view, not
| only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.
|
| app_errorhandler(self, code: 'type[Exception] | int') -> 't.Callable[[T_error_handler], T_error_handler]'
| Like :meth:`errorhandler`, but for every request, not only those handled by
| the blueprint. Equivalent to :meth:`.Flask.errorhandler`.
|
| app_template_filter(self, name: 'str | None' = None) -> 't.Callable[[T_template_filter], T_template_filter]'
| Register a template filter, available in any template rendered by the
| application. Equivalent to :meth:`.Flask.template_filter`.
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| app_template_global(self, name: 'str | None' = None) -> 't.Callable[[T_template_global], T_template_global]'
| Register a template global, available in any template rendered by the
| application. Equivalent to :meth:`.Flask.template_global`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global, otherwise the
| function name will be used.
|
| app_template_test(self, name: 'str | None' = None) -> 't.Callable[[T_template_test], T_template_test]'
| Register a template test, available in any template rendered by the
| application. Equivalent to :meth:`.Flask.template_test`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| app_url_defaults(self, f: 'T_url_defaults') -> 'T_url_defaults'
| Like :meth:`url_defaults`, but for every request, not only those handled by
| the blueprint. Equivalent to :meth:`.Flask.url_defaults`.
|
| app_url_value_preprocessor(self, f: 'T_url_value_preprocessor') -> 'T_url_value_preprocessor'
| Like :meth:`url_value_preprocessor`, but for every request, not only those
| handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.
|
| before_app_request(self, f: 'T_before_request') -> 'T_before_request'
| Like :meth:`before_request`, but before every request, not only those handled
| by the blueprint. Equivalent to :meth:`.Flask.before_request`.
|
| make_setup_state(self, app: 'App', options: 'dict[str, t.Any]', first_registration: 'bool' = False) -> 'BlueprintSetupState'
| Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
| object that is later passed to the register callback functions.
| Subclasses can override this to return a subclass of the setup state.
|
| record(self, func: 'DeferredSetupFunction') -> '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 :meth:`make_setup_state`
| method.
|
| record_once(self, func: 'DeferredSetupFunction') -> 'None'
| Works like :meth:`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(self, app: 'App', options: 'dict[str, t.Any]') -> 'None'
| Called by :meth:`Flask.register_blueprint` to register all
| views and callbacks registered on the blueprint with the
| application. Creates a :class:`.BlueprintSetupState` and calls
| each :meth:`record` callback with it.
|
| :param app: The application this blueprint is being registered
| with.
| :param options: Keyword arguments forwarded from
| :meth:`~Flask.register_blueprint`.
|
| .. versionchanged:: 2.3
| Nested blueprints now correctly apply subdomains.
|
| .. versionchanged:: 2.1
| Registering the same blueprint with the same name multiple
| times is an error.
|
| .. versionchanged:: 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.
|
| .. versionchanged:: 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(self, blueprint: 'Blueprint', **options: 't.Any') -> 'None'
| Register a :class:`~flask.Blueprint` on this blueprint. Keyword
| arguments passed to this method will override the defaults set
| on the blueprint.
|
| .. versionchanged:: 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``.
|
| .. versionadded:: 2.0
|
| teardown_app_request(self, f: 'T_teardown') -> 'T_teardown'
| Like :meth:`teardown_request`, but after every request, not only those
| handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.scaffold.Scaffold:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| after_request(self, 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 :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`.
|
| before_request(self, 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.
|
| .. 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`.
|
| context_processor(self, 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 :meth:`.Blueprint.app_context_processor`.
|
| delete(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["DELETE"]``.
|
| .. versionadded:: 2.0
|
| endpoint(self, endpoint: 'str') -> 't.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
| :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.
|
| errorhandler(self, code_or_exception: 'type[Exception] | int') -> 't.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 :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
|
| get(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["GET"]``.
|
| .. versionadded:: 2.0
|
| patch(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PATCH"]``.
|
| .. versionadded:: 2.0
|
| post(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["POST"]``.
|
| .. versionadded:: 2.0
|
| put(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PUT"]``.
|
| .. versionadded:: 2.0
|
| register_error_handler(self, code_or_exception: 'type[Exception] | int', f: 'ft.ErrorHandlerCallable') -> 'None'
| Alternative error attach function to the :meth:`errorhandler`
| decorator that is more straightforward to use for non decorator
| usage.
|
| .. versionadded:: 0.7
|
| route(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_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.
|
| .. 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.
|
| teardown_request(self, 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.
|
| .. 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`.
|
| url_defaults(self, 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 :meth:`.Blueprint.app_url_defaults`.
|
| url_value_preprocessor(self, 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
| :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`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from flask.sansio.scaffold.Scaffold:
|
| has_static_folder
| ``True`` if :attr:`static_folder` is set.
|
| .. versionadded:: 0.5
|
| 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.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data descriptors inherited from flask.sansio.scaffold.Scaffold:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| static_folder
| The absolute path to the configured static folder. ``None``
| if no static folder is set.
|
| static_url_path
| 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`.
flask.Config
Python Library Documentation: class Config in module flask.config
class Config(builtins.dict)
| Config(root_path: 'str | os.PathLike[str]', defaults: 'dict[str, t.Any] | None' = None) -> 'None'
|
| Works exactly like a dict but provides ways to fill it from files
| or special dictionaries. There are two common patterns to populate the
| config.
|
| Either you can fill the config from a config file::
|
| app.config.from_pyfile('yourconfig.cfg')
|
| Or alternatively you can define the configuration options in the
| module that calls :meth:`from_object` or provide an import path to
| a module that should be loaded. It is also possible to tell it to
| use the same module and with that provide the configuration values
| just before the call::
|
| DEBUG = True
| SECRET_KEY = 'development key'
| app.config.from_object(__name__)
|
| In both cases (loading from any Python file or loading from modules),
| only uppercase keys are added to the config. This makes it possible to use
| lowercase values in the config file for temporary values that are not added
| to the config or to define the config keys in the same file that implements
| the application.
|
| Probably the most interesting way to load configurations is from an
| environment variable pointing to a file::
|
| app.config.from_envvar('YOURAPPLICATION_SETTINGS')
|
| In this case before launching the application you have to set this
| environment variable to the file you want to use. On Linux and OS X
| use the export statement::
|
| export YOURAPPLICATION_SETTINGS='/path/to/config/file'
|
| On windows use `set` instead.
|
| :param root_path: path to which files are read relative from. When the
| config object is created by the application, this is
| the application's :attr:`~flask.Flask.root_path`.
| :param defaults: an optional dictionary of default values
|
| Method resolution order:
| Config
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __init__(self, root_path: 'str | os.PathLike[str]', defaults: 'dict[str, t.Any] | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| from_envvar(self, variable_name: 'str', silent: 'bool' = False) -> 'bool'
| Loads a configuration from an environment variable pointing to
| a configuration file. This is basically just a shortcut with nicer
| error messages for this line of code::
|
| app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
|
| :param variable_name: name of the environment variable
| :param silent: set to ``True`` if you want silent failure for missing
| files.
| :return: ``True`` if the file was loaded successfully.
|
| from_file(self, filename: 'str | os.PathLike[str]', load: 't.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]]', silent: 'bool' = False, text: 'bool' = True) -> 'bool'
| Update the values in the config from a file that is loaded
| using the ``load`` parameter. The loaded data is passed to the
| :meth:`from_mapping` method.
|
| .. code-block:: python
|
| import json
| app.config.from_file("config.json", load=json.load)
|
| import tomllib
| app.config.from_file("config.toml", load=tomllib.load, text=False)
|
| :param filename: The path to the data file. This can be an
| absolute path or relative to the config root path.
| :param load: A callable that takes a file handle and returns a
| mapping of loaded data from the file.
| :type load: ``Callable[[Reader], Mapping]`` where ``Reader``
| implements a ``read`` method.
| :param silent: Ignore the file if it doesn't exist.
| :param text: Open the file in text or binary mode.
| :return: ``True`` if the file was loaded successfully.
|
| .. versionchanged:: 2.3
| The ``text`` parameter was added.
|
| .. versionadded:: 2.0
|
| from_mapping(self, mapping: 't.Mapping[str, t.Any] | None' = None, **kwargs: 't.Any') -> 'bool'
| Updates the config like :meth:`update` ignoring items with
| non-upper keys.
|
| :return: Always returns ``True``.
|
| .. versionadded:: 0.11
|
| from_object(self, obj: 'object | str') -> 'None'
| Updates the values from the given object. An object can be of one
| of the following two types:
|
| - a string: in this case the object with that name will be imported
| - an actual object reference: that object is used directly
|
| Objects are usually either modules or classes. :meth:`from_object`
| loads only the uppercase attributes of the module/class. A ``dict``
| object will not work with :meth:`from_object` because the keys of a
| ``dict`` are not attributes of the ``dict`` class.
|
| Example of module-based configuration::
|
| app.config.from_object('yourapplication.default_config')
| from yourapplication import default_config
| app.config.from_object(default_config)
|
| Nothing is done to the object before loading. If the object is a
| class and has ``@property`` attributes, it needs to be
| instantiated before being passed to this method.
|
| You should not use this function to load the actual configuration but
| rather configuration defaults. The actual config should be loaded
| with :meth:`from_pyfile` and ideally from a location not within the
| package because the package might be installed system wide.
|
| See :ref:`config-dev-prod` for an example of class-based configuration
| using :meth:`from_object`.
|
| :param obj: an import name or object
|
| from_prefixed_env(self, prefix: 'str' = 'FLASK', *, loads: 't.Callable[[str], t.Any]' = <function loads at 0x0000023206713560>) -> 'bool'
| Load any environment variables that start with ``FLASK_``,
| dropping the prefix from the env key for the config key. Values
| are passed through a loading function to attempt to convert them
| to more specific types than strings.
|
| Keys are loaded in :func:`sorted` order.
|
| The default loading function attempts to parse values as any
| valid JSON type, including dicts and lists.
|
| Specific items in nested dicts can be set by separating the
| keys with double underscores (``__``). If an intermediate key
| doesn't exist, it will be initialized to an empty dict.
|
| :param prefix: Load env vars that start with this prefix,
| separated with an underscore (``_``).
| :param loads: Pass each string value to this function and use
| the returned value as the config value. If any error is
| raised it is ignored and the value remains a string. The
| default is :func:`json.loads`.
|
| .. versionadded:: 2.1
|
| from_pyfile(self, filename: 'str | os.PathLike[str]', silent: 'bool' = False) -> 'bool'
| Updates the values in the config from a Python file. This function
| behaves as if the file was imported as module with the
| :meth:`from_object` function.
|
| :param filename: the filename of the config. This can either be an
| absolute filename or a filename relative to the
| root path.
| :param silent: set to ``True`` if you want silent failure for missing
| files.
| :return: ``True`` if the file was loaded successfully.
|
| .. versionadded:: 0.7
| `silent` parameter.
|
| get_namespace(self, namespace: 'str', lowercase: 'bool' = True, trim_namespace: 'bool' = True) -> 'dict[str, t.Any]'
| Returns a dictionary containing a subset of configuration options
| that match the specified namespace/prefix. Example usage::
|
| app.config['IMAGE_STORE_TYPE'] = 'fs'
| app.config['IMAGE_STORE_PATH'] = '/var/app/images'
| app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
| image_store_config = app.config.get_namespace('IMAGE_STORE_')
|
| The resulting dictionary `image_store_config` would look like::
|
| {
| 'type': 'fs',
| 'path': '/var/app/images',
| 'base_url': 'http://img.website.com'
| }
|
| This is often useful when configuration options map directly to
| keyword arguments in functions or class constructors.
|
| :param namespace: a configuration namespace
| :param lowercase: a flag indicating if the keys of the resulting
| dictionary should be lowercase
| :param trim_namespace: a flag indicating if the keys of the resulting
| dictionary should not include the namespace
|
| .. versionadded:: 0.11
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from builtins.dict:
|
| __hash__ = None
flask.Flask
Python Library Documentation: class Flask in module flask.app
class Flask(flask.sansio.app.App)
| Flask(import_name: 'str', static_url_path: 'str | None' = None, static_folder: 'str | os.PathLike[str] | None' = 'static', static_host: 'str | None' = None, host_matching: 'bool' = False, subdomain_matching: 'bool' = False, template_folder: 'str | os.PathLike[str] | None' = 'templates', instance_path: 'str | None' = None, instance_relative_config: 'bool' = False, root_path: 'str | None' = None)
|
| The flask object implements a WSGI application and acts as the central
| object. It is passed the name of the module or package of the
| application. Once it is created it will act as a central registry for
| the view functions, the URL rules, template configuration and much more.
|
| The name of the package is used to resolve resources from inside the
| package or the folder the module is contained in depending on if the
| package parameter resolves to an actual python package (a folder with
| an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
|
| For more information about resource loading, see :func:`open_resource`.
|
| Usually you create a :class:`Flask` instance in your main module or
| in the :file:`__init__.py` file of your package like this::
|
| from flask import Flask
| app = Flask(__name__)
|
| .. admonition:: About the First Parameter
|
| The idea of the first parameter is to give Flask an idea of what
| belongs to your application. This name is used to find resources
| on the filesystem, can be used by extensions to improve debugging
| information and a lot more.
|
| So it's important what you provide there. If you are using a single
| module, `__name__` is always the correct value. If you however are
| using a package, it's usually recommended to hardcode the name of
| your package there.
|
| For example if your application is defined in :file:`yourapplication/app.py`
| you should create it with one of the two versions below::
|
| app = Flask('yourapplication')
| app = Flask(__name__.split('.')[0])
|
| Why is that? The application will work even with `__name__`, thanks
| to how resources are looked up. However it will make debugging more
| painful. Certain extensions can make assumptions based on the
| import name of your application. For example the Flask-SQLAlchemy
| extension will look for the code in your application that triggered
| an SQL query in debug mode. If the import name is not properly set
| up, that debugging information is lost. (For example it would only
| pick up SQL queries in `yourapplication.app` and not
| `yourapplication.views.frontend`)
|
| .. versionadded:: 0.7
| The `static_url_path`, `static_folder`, and `template_folder`
| parameters were added.
|
| .. versionadded:: 0.8
| The `instance_path` and `instance_relative_config` parameters were
| added.
|
| .. versionadded:: 0.11
| The `root_path` parameter was added.
|
| .. versionadded:: 1.0
| The ``host_matching`` and ``static_host`` parameters were added.
|
| .. versionadded:: 1.0
| The ``subdomain_matching`` parameter was added. Subdomain
| matching needs to be enabled manually now. Setting
| :data:`SERVER_NAME` does not implicitly enable it.
|
| :param import_name: the name of the application package
| :param static_url_path: can be used to specify a different path for the
| static files on the web. Defaults to the name
| of the `static_folder` folder.
| :param static_folder: The folder with static files that is served at
| ``static_url_path``. Relative to the application ``root_path``
| or an absolute path. Defaults to ``'static'``.
| :param static_host: the host to use when adding the static route.
| Defaults to None. Required when using ``host_matching=True``
| with a ``static_folder`` configured.
| :param host_matching: set ``url_map.host_matching`` attribute.
| Defaults to False.
| :param subdomain_matching: consider the subdomain relative to
| :data:`SERVER_NAME` when matching routes. Defaults to False.
| :param template_folder: the folder that contains the templates that should
| be used by the application. Defaults to
| ``'templates'`` folder in the root path of the
| application.
| :param instance_path: An alternative instance path for the application.
| By default the folder ``'instance'`` next to the
| package or module is assumed to be the instance
| path.
| :param instance_relative_config: if set to ``True`` relative filenames
| for loading the config are assumed to
| be relative to the instance path instead
| of the application root.
| :param root_path: The path to the root of the application files.
| This should only be set manually when it can't be detected
| automatically, such as for namespace packages.
|
| Method resolution order:
| Flask
| flask.sansio.app.App
| flask.sansio.scaffold.Scaffold
| builtins.object
|
| Methods defined here:
|
| __call__(self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 'cabc.Iterable[bytes]'
| The WSGI server calls the Flask application object as the
| WSGI application. This calls :meth:`wsgi_app`, which can be
| wrapped to apply middleware.
|
| __init__(self, import_name: 'str', static_url_path: 'str | None' = None, static_folder: 'str | os.PathLike[str] | None' = 'static', static_host: 'str | None' = None, host_matching: 'bool' = False, subdomain_matching: 'bool' = False, template_folder: 'str | os.PathLike[str] | None' = 'templates', instance_path: 'str | None' = None, instance_relative_config: 'bool' = False, root_path: 'str | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| app_context(self) -> 'AppContext'
| Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
| block to push the context, which will make :data:`current_app`
| point at this application.
|
| An application context is automatically pushed by
| :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
| when handling a request, and when running a CLI command. Use
| this to manually create a context outside of these situations.
|
| ::
|
| with app.app_context():
| init_db()
|
| See :doc:`/appcontext`.
|
| .. versionadded:: 0.9
|
| async_to_sync(self, func: 't.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]') -> 't.Callable[..., t.Any]'
| Return a sync function that will run the coroutine function.
|
| .. code-block:: python
|
| result = app.async_to_sync(func)(*args, **kwargs)
|
| Override this method to change how the app converts async code
| to be synchronously callable.
|
| .. versionadded:: 2.0
|
| create_jinja_environment(self) -> 'Environment'
| Create the Jinja environment based on :attr:`jinja_options`
| and the various Jinja-related methods of the app. Changing
| :attr:`jinja_options` after this will have no effect. Also adds
| Flask-related globals and filters to the environment.
|
| .. versionchanged:: 0.11
| ``Environment.auto_reload`` set in accordance with
| ``TEMPLATES_AUTO_RELOAD`` configuration option.
|
| .. versionadded:: 0.5
|
| create_url_adapter(self, request: 'Request | None') -> 'MapAdapter | None'
| Creates a URL adapter for the given request. The URL adapter
| is created at a point where the request context is not yet set
| up so the request is passed explicitly.
|
| .. versionchanged:: 3.1
| If :data:`SERVER_NAME` is set, it does not restrict requests to
| only that domain, for both ``subdomain_matching`` and
| ``host_matching``.
|
| .. versionchanged:: 1.0
| :data:`SERVER_NAME` no longer implicitly enables subdomain
| matching. Use :attr:`subdomain_matching` instead.
|
| .. versionchanged:: 0.9
| This can be called outside a request when the URL adapter is created
| for an application context.
|
| .. versionadded:: 0.6
|
| dispatch_request(self) -> 'ft.ResponseReturnValue'
| Does the request dispatching. Matches the URL and returns the
| return value of the view or error handler. This does not have to
| be a response object. In order to convert the return value to a
| proper response object, call :func:`make_response`.
|
| .. versionchanged:: 0.7
| This no longer does the exception handling, this code was
| moved to the new :meth:`full_dispatch_request`.
|
| do_teardown_appcontext(self, exc: 'BaseException | None' = <object object at 0x00000232059594F0>) -> 'None'
| Called right before the application context is popped.
|
| When handling a request, the application context is popped
| after the request context. See :meth:`do_teardown_request`.
|
| This calls all functions decorated with
| :meth:`teardown_appcontext`. Then the
| :data:`appcontext_tearing_down` signal is sent.
|
| This is called by
| :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
|
| .. versionadded:: 0.9
|
| do_teardown_request(self, exc: 'BaseException | None' = <object object at 0x00000232059594F0>) -> 'None'
| Called after the request is dispatched and the response is
| returned, right before the request context is popped.
|
| This calls all functions decorated with
| :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
| if a blueprint handled the request. Finally, the
| :data:`request_tearing_down` signal is sent.
|
| This is called by
| :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
| which may be delayed during testing to maintain access to
| resources.
|
| :param exc: An unhandled exception raised while dispatching the
| request. Detected from the current exception information if
| not passed. Passed to each teardown function.
|
| .. versionchanged:: 0.9
| Added the ``exc`` argument.
|
| ensure_sync(self, func: 't.Callable[..., t.Any]') -> 't.Callable[..., t.Any]'
| Ensure that the function is synchronous for WSGI workers.
| Plain ``def`` functions are returned as-is. ``async def``
| functions are wrapped to run and wait for the response.
|
| Override this method to change how the app runs async views.
|
| .. versionadded:: 2.0
|
| finalize_request(self, rv: 'ft.ResponseReturnValue | HTTPException', from_error_handler: 'bool' = False) -> 'Response'
| Given the return value from a view function this finalizes
| the request by converting it into a response and invoking the
| postprocessing functions. This is invoked for both normal
| request dispatching as well as error handlers.
|
| Because this means that it might be called as a result of a
| failure a special safe mode is available which can be enabled
| with the `from_error_handler` flag. If enabled, failures in
| response processing will be logged and otherwise ignored.
|
| :internal:
|
| full_dispatch_request(self) -> 'Response'
| Dispatches the request and on top of that performs request
| pre and postprocessing as well as HTTP exception catching and
| error handling.
|
| .. versionadded:: 0.7
|
| get_send_file_max_age(self, filename: 'str | None') -> 'int | None'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionchanged:: 2.0
| The default configuration is ``None`` instead of 12 hours.
|
| .. versionadded:: 0.9
|
| handle_exception(self, e: 'Exception') -> 'Response'
| Handle an exception that did not have an error handler
| associated with it, or that was raised from an error handler.
| This always causes a 500 ``InternalServerError``.
|
| Always sends the :data:`got_request_exception` signal.
|
| If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug
| mode, the error will be re-raised so that the debugger can
| display it. Otherwise, the original exception is logged, and
| an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
|
| If an error handler is registered for ``InternalServerError`` or
| ``500``, it will be used. For consistency, the handler will
| always receive the ``InternalServerError``. The original
| unhandled exception is available as ``e.original_exception``.
|
| .. versionchanged:: 1.1.0
| Always passes the ``InternalServerError`` instance to the
| handler, setting ``original_exception`` to the unhandled
| error.
|
| .. versionchanged:: 1.1.0
| ``after_request`` functions and other finalization is done
| even for the default 500 response when there is no handler.
|
| .. versionadded:: 0.3
|
| handle_http_exception(self, e: 'HTTPException') -> 'HTTPException | ft.ResponseReturnValue'
| Handles an HTTP exception. By default this will invoke the
| registered error handlers and fall back to returning the
| exception as response.
|
| .. versionchanged:: 1.0.3
| ``RoutingException``, used internally for actions such as
| slash redirects during routing, is not passed to error
| handlers.
|
| .. versionchanged:: 1.0
| Exceptions are looked up by code *and* by MRO, so
| ``HTTPException`` subclasses can be handled with a catch-all
| handler for the base ``HTTPException``.
|
| .. versionadded:: 0.3
|
| handle_user_exception(self, e: 'Exception') -> 'HTTPException | ft.ResponseReturnValue'
| This method is called whenever an exception occurs that
| should be handled. A special case is :class:`~werkzeug
| .exceptions.HTTPException` which is forwarded to the
| :meth:`handle_http_exception` method. This function will either
| return a response value or reraise the exception with the same
| traceback.
|
| .. versionchanged:: 1.0
| Key errors raised from request data like ``form`` show the
| bad key in debug mode rather than a generic bad request
| message.
|
| .. versionadded:: 0.7
|
| log_exception(self, exc_info: 'tuple[type, BaseException, TracebackType] | tuple[None, None, None]') -> 'None'
| Logs an exception. This is called by :meth:`handle_exception`
| if debugging is disabled and right before the handler is called.
| The default implementation logs the exception as error on the
| :attr:`logger`.
|
| .. versionadded:: 0.8
|
| make_default_options_response(self) -> 'Response'
| This method is called to create the default ``OPTIONS`` response.
| This can be changed through subclassing to change the default
| behavior of ``OPTIONS`` responses.
|
| .. versionadded:: 0.7
|
| make_response(self, rv: 'ft.ResponseReturnValue') -> 'Response'
| Convert the return value from a view function to an instance of
| :attr:`response_class`.
|
| :param rv: the return value from the view function. The view function
| must return a response. Returning ``None``, or the view ending
| without returning, is not allowed. The following types are allowed
| for ``view_rv``:
|
| ``str``
| A response object is created with the string encoded to UTF-8
| as the body.
|
| ``bytes``
| A response object is created with the bytes as the body.
|
| ``dict``
| A dictionary that will be jsonify'd before being returned.
|
| ``list``
| A list that will be jsonify'd before being returned.
|
| ``generator`` or ``iterator``
| A generator that returns ``str`` or ``bytes`` to be
| streamed as the response.
|
| ``tuple``
| Either ``(body, status, headers)``, ``(body, status)``, or
| ``(body, headers)``, where ``body`` is any of the other types
| allowed here, ``status`` is a string or an integer, and
| ``headers`` is a dictionary or a list of ``(key, value)``
| tuples. If ``body`` is a :attr:`response_class` instance,
| ``status`` overwrites the exiting value and ``headers`` are
| extended.
|
| :attr:`response_class`
| The object is returned unchanged.
|
| other :class:`~werkzeug.wrappers.Response` class
| The object is coerced to :attr:`response_class`.
|
| :func:`callable`
| The function is called as a WSGI application. The result is
| used to create a response object.
|
| .. versionchanged:: 2.2
| A generator will be converted to a streaming response.
| A list will be converted to a JSON response.
|
| .. versionchanged:: 1.1
| A dict will be converted to a JSON response.
|
| .. versionchanged:: 0.9
| Previously a tuple was interpreted as the arguments for the
| response object.
|
| make_shell_context(self) -> 'dict[str, t.Any]'
| Returns the shell context for an interactive shell for this
| application. This runs all the registered shell context
| processors.
|
| .. versionadded:: 0.11
|
| open_instance_resource(self, resource: 'str', mode: 'str' = 'rb', encoding: 'str | None' = 'utf-8') -> 't.IO[t.AnyStr]'
| Open a resource file relative to the application's instance folder
| :attr:`instance_path`. Unlike :meth:`open_resource`, files in the
| instance folder can be opened for writing.
|
| :param resource: Path to the resource relative to :attr:`instance_path`.
| :param mode: Open the file in this mode.
| :param encoding: Open the file with this encoding when opening in text
| mode. This is ignored when opening in binary mode.
|
| .. versionchanged:: 3.1
| Added the ``encoding`` parameter.
|
| open_resource(self, resource: 'str', mode: 'str' = 'rb', encoding: 'str | None' = None) -> 't.IO[t.AnyStr]'
| 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"``.
| :param encoding: Open the file with this encoding when opening in text
| mode. This is ignored when opening in binary mode.
|
| .. versionchanged:: 3.1
| Added the ``encoding`` parameter.
|
| preprocess_request(self) -> 'ft.ResponseReturnValue | None'
| Called before the request is dispatched. Calls
| :attr:`url_value_preprocessors` registered with the app and the
| current blueprint (if any). Then calls :attr:`before_request_funcs`
| registered with the app and the blueprint.
|
| If any :meth:`before_request` handler 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.
|
| process_response(self, response: 'Response') -> 'Response'
| Can be overridden in order to modify the response object
| before it's sent to the WSGI server. By default this will
| call all the :meth:`after_request` decorated functions.
|
| .. versionchanged:: 0.5
| As of Flask 0.5 the functions registered for after request
| execution are called in reverse order of registration.
|
| :param response: a :attr:`response_class` object.
| :return: a new response object or the same, has to be an
| instance of :attr:`response_class`.
|
| raise_routing_exception(self, request: 'Request') -> 't.NoReturn'
| Intercept routing exceptions and possibly do something else.
|
| In debug mode, intercept a routing redirect and replace it with
| an error if the body will be discarded.
|
| With modern Werkzeug this shouldn't occur, since it now uses a
| 308 status which tells the browser to resend the method and
| body.
|
| .. versionchanged:: 2.1
| Don't intercept 307 and 308 redirects.
|
| :meta private:
| :internal:
|
| request_context(self, environ: 'WSGIEnvironment') -> 'RequestContext'
| Create a :class:`~flask.ctx.RequestContext` representing a
| WSGI environment. Use a ``with`` block to push the context,
| which will make :data:`request` point at this request.
|
| See :doc:`/reqcontext`.
|
| Typically you should not call this from your own code. A request
| context is automatically pushed by the :meth:`wsgi_app` when
| handling a request. Use :meth:`test_request_context` to create
| an environment and context instead of this method.
|
| :param environ: a WSGI environment
|
| run(self, host: 'str | None' = None, port: 'int | None' = None, debug: 'bool | None' = None, load_dotenv: 'bool' = True, **options: 't.Any') -> 'None'
| Runs the application on a local development server.
|
| Do not use ``run()`` in a production setting. It is not intended to
| meet security and performance requirements for a production server.
| Instead, see :doc:`/deploying/index` for WSGI server recommendations.
|
| If the :attr:`debug` flag is set the server will automatically reload
| for code changes and show a debugger in case an exception happened.
|
| If you want to run the application in debug mode, but disable the
| code execution on the interactive debugger, you can pass
| ``use_evalex=False`` as parameter. This will keep the debugger's
| traceback screen active, but disable code execution.
|
| It is not recommended to use this function for development with
| automatic reloading as this is badly supported. Instead you should
| be using the :command:`flask` command line script's ``run`` support.
|
| .. admonition:: Keep in Mind
|
| Flask will suppress any server error with a generic error page
| unless it is in debug mode. As such to enable just the
| interactive debugger without the code reloading, you have to
| invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
| Setting ``use_debugger`` to ``True`` without being in debug mode
| won't catch any exceptions because there won't be any to
| catch.
|
| :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
| have the server available externally as well. Defaults to
| ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
| if present.
| :param port: the port of the webserver. Defaults to ``5000`` or the
| port defined in the ``SERVER_NAME`` config variable if present.
| :param debug: if given, enable or disable debug mode. See
| :attr:`debug`.
| :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
| files to set environment variables. Will also change the working
| directory to the directory containing the first file found.
| :param options: the options to be forwarded to the underlying Werkzeug
| server. See :func:`werkzeug.serving.run_simple` for more
| information.
|
| .. versionchanged:: 1.0
| If installed, python-dotenv will be used to load environment
| variables from :file:`.env` and :file:`.flaskenv` files.
|
| The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.
|
| Threaded mode is enabled by default.
|
| .. versionchanged:: 0.10
| The default port is now picked from the ``SERVER_NAME``
| variable.
|
| send_static_file(self, filename: 'str') -> 'Response'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionadded:: 0.5
|
| test_cli_runner(self, **kwargs: 't.Any') -> 'FlaskCliRunner'
| Create a CLI runner for testing CLI commands.
| See :ref:`testing-cli`.
|
| Returns an instance of :attr:`test_cli_runner_class`, by default
| :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
| passed as the first argument.
|
| .. versionadded:: 1.0
|
| test_client(self, use_cookies: 'bool' = True, **kwargs: 't.Any') -> 'FlaskClient'
| Creates a test client for this application. For information
| about unit testing head over to :doc:`/testing`.
|
| Note that if you are testing for assertions or exceptions in your
| application code, you must set ``app.testing = True`` in order for the
| exceptions to propagate to the test client. Otherwise, the exception
| will be handled by the application (not visible to the test client) and
| the only indication of an AssertionError or other exception will be a
| 500 status code response to the test client. See the :attr:`testing`
| attribute. For example::
|
| app.testing = True
| client = app.test_client()
|
| The test client can be used in a ``with`` block to defer the closing down
| of the context until the end of the ``with`` block. This is useful if
| you want to access the context locals for testing::
|
| with app.test_client() as c:
| rv = c.get('/?vodka=42')
| assert request.args['vodka'] == '42'
|
| Additionally, you may pass optional keyword arguments that will then
| be passed to the application's :attr:`test_client_class` constructor.
| For example::
|
| from flask.testing import FlaskClient
|
| class CustomClient(FlaskClient):
| def __init__(self, *args, **kwargs):
| self._authentication = kwargs.pop("authentication")
| super(CustomClient,self).__init__( *args, **kwargs)
|
| app.test_client_class = CustomClient
| client = app.test_client(authentication='Basic ....')
|
| See :class:`~flask.testing.FlaskClient` for more information.
|
| .. versionchanged:: 0.4
| added support for ``with`` block usage for the client.
|
| .. versionadded:: 0.7
| The `use_cookies` parameter was added as well as the ability
| to override the client to be used by setting the
| :attr:`test_client_class` attribute.
|
| .. versionchanged:: 0.11
| Added `**kwargs` to support passing additional keyword arguments to
| the constructor of :attr:`test_client_class`.
|
| test_request_context(self, *args: 't.Any', **kwargs: 't.Any') -> 'RequestContext'
| Create a :class:`~flask.ctx.RequestContext` for a WSGI
| environment created from the given values. This is mostly useful
| during testing, where you may want to run a function that uses
| request data without dispatching a full request.
|
| See :doc:`/reqcontext`.
|
| Use a ``with`` block to push the context, which will make
| :data:`request` point at the request for the created
| environment. ::
|
| with app.test_request_context(...):
| generate_report()
|
| When using the shell, it may be easier to push and pop the
| context manually to avoid indentation. ::
|
| ctx = app.test_request_context(...)
| ctx.push()
| ...
| ctx.pop()
|
| Takes the same arguments as Werkzeug's
| :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
| the application. See the linked Werkzeug docs for most of the
| available arguments. Flask-specific behavior is listed here.
|
| :param path: URL path being requested.
| :param base_url: Base URL where the app is being served, which
| ``path`` is relative to. If not given, built from
| :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
| :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
| :param subdomain: Subdomain name to append to
| :data:`SERVER_NAME`.
| :param url_scheme: Scheme to use instead of
| :data:`PREFERRED_URL_SCHEME`.
| :param data: The request body, either as a string or a dict of
| form keys and values.
| :param json: If given, this is serialized as JSON and passed as
| ``data``. Also defaults ``content_type`` to
| ``application/json``.
| :param args: other positional arguments passed to
| :class:`~werkzeug.test.EnvironBuilder`.
| :param kwargs: other keyword arguments passed to
| :class:`~werkzeug.test.EnvironBuilder`.
|
| update_template_context(self, context: 'dict[str, t.Any]') -> 'None'
| Update the template context with some commonly used variables.
| This injects request, session, config and g into the template
| context as well as everything template context processors want
| to inject. Note that the as of Flask 0.6, the original values
| in the context will not be overridden if a context processor
| decides to return a value with the same key.
|
| :param context: the context as a dictionary that is updated in place
| to add extra variables.
|
| url_for(self, /, endpoint: 'str', *, _anchor: 'str | None' = None, _method: 'str | None' = None, _scheme: 'str | None' = None, _external: 'bool | None' = None, **values: 't.Any') -> 'str'
| Generate a URL to the given endpoint with the given values.
|
| This is called by :func:`flask.url_for`, and can be called
| directly as well.
|
| An *endpoint* is the name of a URL rule, usually added with
| :meth:`@app.route() <route>`, and usually the same name as the
| view function. A route defined in a :class:`~flask.Blueprint`
| will prepend the blueprint's name separated by a ``.`` to the
| endpoint.
|
| In some cases, such as email messages, you want URLs to include
| the scheme and domain, like ``https://example.com/hello``. When
| not in an active request, URLs will be external by default, but
| this requires setting :data:`SERVER_NAME` so Flask knows what
| domain to use. :data:`APPLICATION_ROOT` and
| :data:`PREFERRED_URL_SCHEME` should also be configured as
| needed. This config is only used when not in an active request.
|
| Functions can be decorated with :meth:`url_defaults` to modify
| keyword arguments before the URL is built.
|
| If building fails for some reason, such as an unknown endpoint
| or incorrect values, the app's :meth:`handle_url_build_error`
| method is called. If that returns a string, that is returned,
| otherwise a :exc:`~werkzeug.routing.BuildError` is raised.
|
| :param endpoint: The endpoint name associated with the URL to
| generate. If this starts with a ``.``, the current blueprint
| name (if any) will be used.
| :param _anchor: If given, append this as ``#anchor`` to the URL.
| :param _method: If given, generate the URL associated with this
| method for the endpoint.
| :param _scheme: If given, the URL will have this scheme if it
| is external.
| :param _external: If given, prefer the URL to be internal
| (False) or require it to be external (True). External URLs
| include the scheme and domain. When not in an active
| request, URLs are external by default.
| :param values: Values to use for the variable parts of the URL
| rule. Unknown keys are appended as query string arguments,
| like ``?a=b&c=d``.
|
| .. versionadded:: 2.2
| Moved from ``flask.url_for``, which calls this method.
|
| wsgi_app(self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 'cabc.Iterable[bytes]'
| The actual WSGI application. This is not implemented in
| :meth:`__call__` so that middlewares can be applied without
| losing a reference to the app object. Instead of doing this::
|
| app = MyMiddleware(app)
|
| It's a better idea to do this instead::
|
| app.wsgi_app = MyMiddleware(app.wsgi_app)
|
| Then you still have the original application object around and
| can continue to call methods on it.
|
| .. versionchanged:: 0.7
| Teardown events for the request and app contexts are called
| even if an unhandled error occurs. Other events may not be
| called depending on when an error occurs during dispatch.
| See :ref:`callbacks-and-errors`.
|
| :param environ: A WSGI environment.
| :param start_response: A callable accepting a status code,
| a list of headers, and an optional exception context to
| start the response.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'request_class': 'type[Request]', 'response_class':...
|
| default_config = ImmutableDict({'DEBUG': None, 'TESTING': False, ..._S...
|
| request_class = <class 'flask.wrappers.Request'>
| The request object used by default in Flask. Remembers the
| matched endpoint and view arguments.
|
| It is what ends up as :class:`~flask.request`. If you want to replace
| the request object used you can subclass this and set
| :attr:`~flask.Flask.request_class` to your subclass.
|
| The request object is a :class:`~werkzeug.wrappers.Request` subclass and
| provides all of the attributes Werkzeug defines plus a few Flask
| specific ones.
|
|
| response_class = <class 'flask.wrappers.Response'>
| The response object that is used by default in Flask. Works like the
| response object from Werkzeug but is set to have an HTML mimetype by
| default. Quite often you don't have to create this object yourself because
| :meth:`~flask.Flask.make_response` will take care of that for you.
|
| If you want to replace the response object used you can subclass this and
| set :attr:`~flask.Flask.response_class` to your subclass.
|
| .. versionchanged:: 1.0
| JSON support is added to the response, like the request. This is useful
| when testing to get the test client response data as JSON.
|
| .. versionchanged:: 1.0
|
| Added :attr:`max_cookie_size`.
|
|
| session_interface = <flask.sessions.SecureCookieSessionInterface objec...
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.app.App:
|
| add_template_filter(self, f: 'ft.TemplateFilterCallable', name: 'str | None' = None) -> 'None'
| Register a custom template filter. Works exactly like the
| :meth:`template_filter` decorator.
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| add_template_global(self, f: 'ft.TemplateGlobalCallable', name: 'str | None' = None) -> 'None'
| Register a custom template global function. Works exactly like the
| :meth:`template_global` decorator.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global function, otherwise the
| function name will be used.
|
| add_template_test(self, f: 'ft.TemplateTestCallable', name: 'str | None' = None) -> 'None'
| Register a custom template test. Works exactly like the
| :meth:`template_test` decorator.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| add_url_rule(self, rule: 'str', endpoint: 'str | None' = None, view_func: 'ft.RouteCallable | None' = None, provide_automatic_options: 'bool | None' = None, **options: 't.Any') -> 'None'
| 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.
|
| auto_find_instance_path(self) -> 'str'
| Tries to locate the instance path if it was not provided to the
| constructor of the application class. It will basically calculate
| the path to a folder named ``instance`` next to your main file or
| the package.
|
| .. versionadded:: 0.8
|
| create_global_jinja_loader(self) -> 'DispatchingJinjaLoader'
| Creates the loader for the Jinja environment. Can be used to
| override just the loader and keeping the rest unchanged. It's
| discouraged to override this function. Instead one should override
| the :meth:`jinja_loader` function instead.
|
| The global loader dispatches between the loaders of the application
| and the individual blueprints.
|
| .. versionadded:: 0.7
|
| handle_url_build_error(self, error: 'BuildError', endpoint: 'str', values: 'dict[str, t.Any]') -> 'str'
| Called by :meth:`.url_for` if a
| :exc:`~werkzeug.routing.BuildError` was raised. If this returns
| a value, it will be returned by ``url_for``, otherwise the error
| will be re-raised.
|
| Each function in :attr:`url_build_error_handlers` is called with
| ``error``, ``endpoint`` and ``values``. If a function returns
| ``None`` or raises a ``BuildError``, it is skipped. Otherwise,
| its return value is returned by ``url_for``.
|
| :param error: The active ``BuildError`` being handled.
| :param endpoint: The endpoint being built.
| :param values: The keyword arguments passed to ``url_for``.
|
| inject_url_defaults(self, endpoint: 'str', values: 'dict[str, t.Any]') -> 'None'
| Injects the URL defaults for the given endpoint directly into
| the values dictionary passed. This is used internally and
| automatically called on URL building.
|
| .. versionadded:: 0.7
|
| iter_blueprints(self) -> 't.ValuesView[Blueprint]'
| Iterates over all blueprints by the order they were registered.
|
| .. versionadded:: 0.11
|
| make_aborter(self) -> 'Aborter'
| Create the object to assign to :attr:`aborter`. That object
| is called by :func:`flask.abort` to raise HTTP errors, and can
| be called directly as well.
|
| By default, this creates an instance of :attr:`aborter_class`,
| which defaults to :class:`werkzeug.exceptions.Aborter`.
|
| .. versionadded:: 2.2
|
| make_config(self, instance_relative: 'bool' = False) -> 'Config'
| Used to create the config attribute by the Flask constructor.
| The `instance_relative` parameter is passed in from the constructor
| of Flask (there named `instance_relative_config`) and indicates if
| the config should be relative to the instance path or the root path
| of the application.
|
| .. versionadded:: 0.8
|
| redirect(self, location: 'str', code: 'int' = 302) -> 'BaseResponse'
| Create a redirect response object.
|
| This is called by :func:`flask.redirect`, and can be called
| directly as well.
|
| :param location: The URL to redirect to.
| :param code: The status code for the redirect.
|
| .. versionadded:: 2.2
| Moved from ``flask.redirect``, which calls this method.
|
| register_blueprint(self, blueprint: 'Blueprint', **options: 't.Any') -> 'None'
| Register a :class:`~flask.Blueprint` on the application. Keyword
| arguments passed to this method will override the defaults set on the
| blueprint.
|
| Calls the blueprint's :meth:`~flask.Blueprint.register` method after
| recording the blueprint in the application's :attr:`blueprints`.
|
| :param blueprint: The blueprint to register.
| :param url_prefix: Blueprint routes will be prefixed with this.
| :param subdomain: Blueprint routes will match on this subdomain.
| :param url_defaults: Blueprint routes will use these default values for
| view arguments.
| :param options: Additional keyword arguments are passed to
| :class:`~flask.blueprints.BlueprintSetupState`. They can be
| accessed in :meth:`~flask.Blueprint.record` callbacks.
|
| .. versionchanged:: 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``.
|
| .. versionadded:: 0.7
|
| select_jinja_autoescape(self, filename: 'str | None') -> 'bool'
| Returns ``True`` if autoescaping should be active for the given
| template name. If no template name is given, returns `True`.
|
| .. versionchanged:: 2.2
| Autoescaping is now enabled by default for ``.svg`` files.
|
| .. versionadded:: 0.5
|
| shell_context_processor(self, f: 'T_shell_context_processor') -> 'T_shell_context_processor'
| Registers a shell context processor function.
|
| .. versionadded:: 0.11
|
| should_ignore_error(self, error: 'BaseException | None') -> 'bool'
| This is called to figure out if an error should be ignored
| or not as far as the teardown system is concerned. If this
| function returns ``True`` then the teardown handlers will not be
| passed the error.
|
| .. versionadded:: 0.10
|
| teardown_appcontext(self, f: 'T_teardown') -> 'T_teardown'
| Registers a function to be called when the application
| context is popped. The application context is typically popped
| after the request context for each request, at the end of CLI
| commands, or after a manually pushed context ends.
|
| .. code-block:: python
|
| with app.app_context():
| ...
|
| When the ``with`` block exits (or ``ctx.pop()`` is called), the
| teardown functions are called just before the app context is
| made inactive. Since a request context typically also manages an
| application context it would also be called when you pop a
| request context.
|
| 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.
|
| .. versionadded:: 0.9
|
| template_filter(self, name: 'str | None' = None) -> 't.Callable[[T_template_filter], T_template_filter]'
| A decorator that is used to register custom template filter.
| You can specify a name for the filter, otherwise the function
| name will be used. Example::
|
| @app.template_filter()
| def reverse(s):
| return s[::-1]
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| template_global(self, name: 'str | None' = None) -> 't.Callable[[T_template_global], T_template_global]'
| A decorator that is used to register a custom template global function.
| You can specify a name for the global function, otherwise the function
| name will be used. Example::
|
| @app.template_global()
| def double(n):
| return 2 * n
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global function, otherwise the
| function name will be used.
|
| template_test(self, name: 'str | None' = None) -> 't.Callable[[T_template_test], T_template_test]'
| A decorator that is used to register custom template test.
| You can specify a name for the test, otherwise the function
| name will be used. Example::
|
| @app.template_test()
| def is_prime(n):
| if n == 2:
| return True
| for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
| if n % i == 0:
| return False
| return True
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| trap_http_exception(self, e: 'Exception') -> 'bool'
| Checks if an HTTP exception should be trapped or not. By default
| this will return ``False`` for all exceptions except for a bad request
| key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
| also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
|
| This is called for all HTTP exceptions raised by a view function.
| If it returns ``True`` for any exception the error handler for this
| exception is not called and it shows up as regular exception in the
| traceback. This is helpful for debugging implicitly raised HTTP
| exceptions.
|
| .. versionchanged:: 1.0
| Bad request errors are not trapped by default in debug mode.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Readonly properties inherited from flask.sansio.app.App:
|
| jinja_env
| The Jinja environment used to load templates.
|
| The environment is created the first time this property is
| accessed. Changing :attr:`jinja_options` after that will have no
| effect.
|
| logger
| A standard Python :class:`~logging.Logger` for the app, with
| the same name as :attr:`name`.
|
| In debug mode, the logger's :attr:`~logging.Logger.level` will
| be set to :data:`~logging.DEBUG`.
|
| If there are no handlers configured, a default handler will be
| added. See :doc:`/logging` for more information.
|
| .. versionchanged:: 1.1.0
| The logger takes the same name as :attr:`name` rather than
| hard-coding ``"flask.app"``.
|
| .. versionchanged:: 1.0.0
| Behavior was simplified. The logger is always named
| ``"flask.app"``. The level is only set during configuration,
| it doesn't check ``app.debug`` each time. Only one format is
| used, not different ones depending on ``app.debug``. No
| handlers are removed, and a handler is only added if no
| handlers are already configured.
|
| .. versionadded:: 0.3
|
| name
| The name of the application. This is usually the import name
| with the difference that it's guessed from the run file if the
| import name is main. This name is used as a display name when
| Flask needs the name of the application. It can be set and overridden
| to change the value.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Data descriptors inherited from flask.sansio.app.App:
|
| debug
| Whether debug mode is enabled. When using ``flask run`` to start the
| development server, an interactive debugger will be shown for unhandled
| exceptions, and the server will be reloaded when code changes. This maps to the
| :data:`DEBUG` config key. It may not behave as expected if set late.
|
| **Do not enable debug mode when deploying in production.**
|
| Default: ``False``
|
| permanent_session_lifetime
|
| secret_key
|
| testing
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from flask.sansio.app.App:
|
| aborter_class = <class 'werkzeug.exceptions.Aborter'>
| When passed a dict of code -> exception items it can be used as
| callable that raises exceptions. If the first argument to the
| callable is an integer it will be looked up in the mapping, if it's
| a WSGI application it will be raised in a proxy exception.
|
| The rest of the arguments are forwarded to the exception constructor.
|
|
| app_ctx_globals_class = <class 'flask.ctx._AppCtxGlobals'>
| A plain object. Used as a namespace for storing data during an
| application context.
|
| Creating an app context automatically creates this object, which is
| made available as the :data:`g` proxy.
|
| .. describe:: 'key' in g
|
| Check whether an attribute is present.
|
| .. versionadded:: 0.10
|
| .. describe:: iter(g)
|
| Return an iterator over the attribute names.
|
| .. versionadded:: 0.10
|
|
| config_class = <class 'flask.config.Config'>
| Works exactly like a dict but provides ways to fill it from files
| or special dictionaries. There are two common patterns to populate the
| config.
|
| Either you can fill the config from a config file::
|
| app.config.from_pyfile('yourconfig.cfg')
|
| Or alternatively you can define the configuration options in the
| module that calls :meth:`from_object` or provide an import path to
| a module that should be loaded. It is also possible to tell it to
| use the same module and with that provide the configuration values
| just before the call::
|
| DEBUG = True
| SECRET_KEY = 'development key'
| app.config.from_object(__name__)
|
| In both cases (loading from any Python file or loading from modules),
| only uppercase keys are added to the config. This makes it possible to use
| lowercase values in the config file for temporary values that are not added
| to the config or to define the config keys in the same file that implements
| the application.
|
| Probably the most interesting way to load configurations is from an
| environment variable pointing to a file::
|
| app.config.from_envvar('YOURAPPLICATION_SETTINGS')
|
| In this case before launching the application you have to set this
| environment variable to the file you want to use. On Linux and OS X
| use the export statement::
|
| export YOURAPPLICATION_SETTINGS='/path/to/config/file'
|
| On windows use `set` instead.
|
| :param root_path: path to which files are read relative from. When the
| config object is created by the application, this is
| the application's :attr:`~flask.Flask.root_path`.
| :param defaults: an optional dictionary of default values
|
|
| jinja_environment = <class 'flask.templating.Environment'>
| Works like a regular Jinja environment but has some additional
| knowledge of how Flask's blueprint works so that it can prepend the
| name of the blueprint to referenced templates if necessary.
|
|
| jinja_options = {}
|
| json_provider_class = <class 'flask.json.provider.DefaultJSONProvider'...
| Provide JSON operations using Python's built-in :mod:`json`
| library. Serializes the following additional data types:
|
| - :class:`datetime.datetime` and :class:`datetime.date` are
| serialized to :rfc:`822` strings. This is the same as the HTTP
| date format.
| - :class:`uuid.UUID` is serialized to a string.
| - :class:`dataclasses.dataclass` is passed to
| :func:`dataclasses.asdict`.
| - :class:`~markupsafe.Markup` (or any object with a ``__html__``
| method) will call the ``__html__`` method to get a string.
|
|
| test_cli_runner_class = None
|
| test_client_class = None
|
| url_map_class = <class 'werkzeug.routing.map.Map'>
| The map class stores all the URL rules and some configuration
| parameters. Some of the configuration values are only stored on the
| `Map` instance since those affect all rules, others are just defaults
| and can be overridden for each rule. Note that you have to specify all
| arguments besides the `rules` as keyword arguments!
|
| :param rules: sequence of url rules for this map.
| :param default_subdomain: The default subdomain for rules without a
| subdomain defined.
| :param strict_slashes: If a rule ends with a slash but the matched
| URL does not, redirect to the URL with a trailing slash.
| :param merge_slashes: Merge consecutive slashes when matching or
| building URLs. Matches will redirect to the normalized URL.
| Slashes in variable parts are not merged.
| :param redirect_defaults: This will redirect to the default rule if it
| wasn't visited that way. This helps creating
| unique URLs.
| :param converters: A dict of converters that adds additional converters
| to the list of converters. If you redefine one
| converter this will override the original one.
| :param sort_parameters: If set to `True` the url parameters are sorted.
| See `url_encode` for more details.
| :param sort_key: The sort key function for `url_encode`.
| :param host_matching: if set to `True` it enables the host matching
| feature and disables the subdomain one. If
| enabled the `host` parameter to rules is used
| instead of the `subdomain` one.
|
| .. versionchanged:: 3.0
| The ``charset`` and ``encoding_errors`` parameters were removed.
|
| .. versionchanged:: 1.0
| If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules will match.
|
| .. versionchanged:: 1.0
| The ``merge_slashes`` parameter was added.
|
| .. versionchanged:: 0.7
| The ``encoding_errors`` and ``host_matching`` parameters were added.
|
| .. versionchanged:: 0.5
| The ``sort_parameters`` and ``sort_key`` parameters were added.
|
|
| url_rule_class = <class 'werkzeug.routing.rules.Rule'>
| A Rule represents one URL pattern. There are some options for `Rule`
| that change the way it behaves and are passed to the `Rule` constructor.
| Note that besides the rule-string all arguments *must* be keyword arguments
| in order to not break the application on Werkzeug upgrades.
|
| `string`
| Rule strings basically are just normal URL paths with placeholders in
| the format ``<converter(arguments):name>`` where the converter and the
| arguments are optional. If no converter is defined the `default`
| converter is used which means `string` in the normal configuration.
|
| URL rules that end with a slash are branch URLs, others are leaves.
| If you have `strict_slashes` enabled (which is the default), all
| branch URLs that are matched without a trailing slash will trigger a
| redirect to the same URL with the missing slash appended.
|
| The converters are defined on the `Map`.
|
| `endpoint`
| The endpoint for this rule. This can be anything. A reference to a
| function, a string, a number etc. The preferred way is using a string
| because the endpoint is used for URL generation.
|
| `defaults`
| An optional dict with defaults for other rules with the same endpoint.
| This is a bit tricky but useful if you want to have unique URLs::
|
| url_map = Map([
| Rule('/all/', defaults={'page': 1}, endpoint='all_entries'),
| Rule('/all/page/<int:page>', endpoint='all_entries')
| ])
|
| If a user now visits ``http://example.com/all/page/1`` they will be
| redirected to ``http://example.com/all/``. If `redirect_defaults` is
| disabled on the `Map` instance this will only affect the URL
| generation.
|
| `subdomain`
| The subdomain rule string for this rule. If not specified the rule
| only matches for the `default_subdomain` of the map. If the map is
| not bound to a subdomain this feature is disabled.
|
| Can be useful if you want to have user profiles on different subdomains
| and all subdomains are forwarded to your application::
|
| url_map = Map([
| Rule('/', subdomain='<username>', endpoint='user/homepage'),
| Rule('/stats', subdomain='<username>', endpoint='user/stats')
| ])
|
| `methods`
| A sequence of http methods this rule applies to. If not specified, all
| methods are allowed. For example this can be useful if you want different
| endpoints for `POST` and `GET`. If methods are defined and the path
| matches but the method matched against is not in this list or in the
| list of another rule for that path the error raised is of the type
| `MethodNotAllowed` rather than `NotFound`. If `GET` is present in the
| list of methods and `HEAD` is not, `HEAD` is added automatically.
|
| `strict_slashes`
| Override the `Map` setting for `strict_slashes` only for this rule. If
| not specified the `Map` setting is used.
|
| `merge_slashes`
| Override :attr:`Map.merge_slashes` for this rule.
|
| `build_only`
| Set this to True and the rule will never match but will create a URL
| that can be build. This is useful if you have resources on a subdomain
| or folder that are not handled by the WSGI application (like static data)
|
| `redirect_to`
| If given this must be either a string or callable. In case of a
| callable it's called with the url adapter that triggered the match and
| the values of the URL as keyword arguments and has to return the target
| for the redirect, otherwise it has to be a string with placeholders in
| rule syntax::
|
| def foo_with_slug(adapter, id):
| # ask the database for the slug for the old id. this of
| # course has nothing to do with werkzeug.
| return f'foo/{Foo.get_slug_for_id(id)}'
|
| url_map = Map([
| Rule('/foo/<slug>', endpoint='foo'),
| Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'),
| Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug)
| ])
|
| When the rule is matched the routing system will raise a
| `RequestRedirect` exception with the target for the redirect.
|
| Keep in mind that the URL will be joined against the URL root of the
| script so don't use a leading slash on the target URL unless you
| really mean root of that domain.
|
| `alias`
| If enabled this rule serves as an alias for another rule with the same
| endpoint and arguments.
|
| `host`
| If provided and the URL map has host matching enabled this can be
| used to provide a match rule for the whole host. This also means
| that the subdomain feature is disabled.
|
| `websocket`
| If ``True``, this rule is only matches for WebSocket (``ws://``,
| ``wss://``) requests. By default, rules will only match for HTTP
| requests.
|
| .. versionchanged:: 2.1
| Percent-encoded newlines (``%0a``), which are decoded by WSGI
| servers, are considered when routing instead of terminating the
| match early.
|
| .. versionadded:: 1.0
| Added ``websocket``.
|
| .. versionadded:: 1.0
| Added ``merge_slashes``.
|
| .. versionadded:: 0.7
| Added ``alias`` and ``host``.
|
| .. versionchanged:: 0.6.1
| ``HEAD`` is added to ``methods`` if ``GET`` is present.
|
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.scaffold.Scaffold:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| after_request(self, 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 :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`.
|
| before_request(self, 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.
|
| .. 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`.
|
| context_processor(self, 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 :meth:`.Blueprint.app_context_processor`.
|
| delete(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["DELETE"]``.
|
| .. versionadded:: 2.0
|
| endpoint(self, endpoint: 'str') -> 't.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
| :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.
|
| errorhandler(self, code_or_exception: 'type[Exception] | int') -> 't.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 :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
|
| get(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["GET"]``.
|
| .. versionadded:: 2.0
|
| patch(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PATCH"]``.
|
| .. versionadded:: 2.0
|
| post(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["POST"]``.
|
| .. versionadded:: 2.0
|
| put(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PUT"]``.
|
| .. versionadded:: 2.0
|
| register_error_handler(self, code_or_exception: 'type[Exception] | int', f: 'ft.ErrorHandlerCallable') -> 'None'
| Alternative error attach function to the :meth:`errorhandler`
| decorator that is more straightforward to use for non decorator
| usage.
|
| .. versionadded:: 0.7
|
| route(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_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.
|
| .. 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.
|
| teardown_request(self, 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.
|
| .. 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`.
|
| url_defaults(self, 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 :meth:`.Blueprint.app_url_defaults`.
|
| url_value_preprocessor(self, 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
| :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`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from flask.sansio.scaffold.Scaffold:
|
| has_static_folder
| ``True`` if :attr:`static_folder` is set.
|
| .. versionadded:: 0.5
|
| 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.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data descriptors inherited from flask.sansio.scaffold.Scaffold:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| static_folder
| The absolute path to the configured static folder. ``None``
| if no static folder is set.
|
| static_url_path
| 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`.
flask.Request
Python Library Documentation: class Request in module flask.wrappers
class Request(werkzeug.wrappers.request.Request)
| Request(environ: 'WSGIEnvironment', populate_request: 'bool' = True, shallow: 'bool' = False) -> 'None'
|
| The request object used by default in Flask. Remembers the
| matched endpoint and view arguments.
|
| It is what ends up as :class:`~flask.request`. If you want to replace
| the request object used you can subclass this and set
| :attr:`~flask.Flask.request_class` to your subclass.
|
| The request object is a :class:`~werkzeug.wrappers.Request` subclass and
| provides all of the attributes Werkzeug defines plus a few Flask
| specific ones.
|
| Method resolution order:
| Request
| werkzeug.wrappers.request.Request
| werkzeug.sansio.request.Request
| builtins.object
|
| Methods defined here:
|
| on_json_loading_failed(self, e: 'ValueError | None') -> 't.Any'
| Called if :meth:`get_json` fails and isn't silenced.
|
| If this method returns a value, it is used as the return value
| for :meth:`get_json`. The default implementation raises
| :exc:`~werkzeug.exceptions.BadRequest`.
|
| :param e: If parsing failed, this is the exception. It will be
| ``None`` if the content type wasn't ``application/json``.
|
| .. versionchanged:: 2.3
| Raise a 415 error instead of 400.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| blueprint
| The registered name of the current blueprint.
|
| This will be ``None`` if the endpoint is not part of a
| blueprint, or if URL matching failed or has not been performed
| yet.
|
| This does not necessarily match the name the blueprint was
| created with. It may have been nested, or registered with a
| different name.
|
| blueprints
| The registered names of the current blueprint upwards through
| parent blueprints.
|
| This will be an empty list if there is no current blueprint, or
| if URL matching failed.
|
| .. versionadded:: 2.0.1
|
| endpoint
| The endpoint that matched the request URL.
|
| This will be ``None`` if matching failed or has not been
| performed yet.
|
| This in combination with :attr:`view_args` can be used to
| reconstruct the same URL or a modified URL.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| max_content_length
| The maximum number of bytes that will be read during this request. If
| this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge`
| error is raised. If it is set to ``None``, no limit is enforced at the
| Flask application level. However, if it is ``None`` and the request has
| no ``Content-Length`` header and the WSGI server does not indicate that
| it terminates the stream, then no data is read to avoid an infinite
| stream.
|
| Each request defaults to the :data:`MAX_CONTENT_LENGTH` config, which
| defaults to ``None``. It can be set on a specific ``request`` to apply
| the limit to that specific view. This should be set appropriately based
| on an application's or view's specific needs.
|
| .. versionchanged:: 3.1
| This can be set per-request.
|
| .. versionchanged:: 0.6
| This is configurable through Flask config.
|
| max_form_memory_size
| The maximum size in bytes any non-file form field may be in a
| ``multipart/form-data`` body. If this limit is exceeded, a 413
| :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it
| is set to ``None``, no limit is enforced at the Flask application level.
|
| Each request defaults to the :data:`MAX_FORM_MEMORY_SIZE` config, which
| defaults to ``500_000``. It can be set on a specific ``request`` to
| apply the limit to that specific view. This should be set appropriately
| based on an application's or view's specific needs.
|
| .. versionchanged:: 3.1
| This is configurable through Flask config.
|
| max_form_parts
| The maximum number of fields that may be present in a
| ``multipart/form-data`` body. If this limit is exceeded, a 413
| :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it
| is set to ``None``, no limit is enforced at the Flask application level.
|
| Each request defaults to the :data:`MAX_FORM_PARTS` config, which
| defaults to ``1_000``. It can be set on a specific ``request`` to apply
| the limit to that specific view. This should be set appropriately based
| on an application's or view's specific needs.
|
| .. versionchanged:: 3.1
| This is configurable through Flask config.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_max_content_length': 'int | None', '_max_form_mem...
|
| json_module = <module 'flask.json' from 'C:\\Users\\Youse\\App...2\\Li...
|
| routing_exception = None
|
| url_rule = None
|
| view_args = None
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.wrappers.request.Request:
|
| __enter__(self) -> 'Request'
|
| __exit__(self, exc_type, exc_value, tb) -> 'None'
|
| __init__(self, environ: 'WSGIEnvironment', populate_request: 'bool' = True, shallow: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| close(self) -> 'None'
| Closes associated resources of this request object. This
| closes all file handles explicitly. You can also use the request
| object in a with statement which will automatically close it.
|
| .. versionadded:: 0.9
|
| get_data(self, cache: 'bool' = True, as_text: 'bool' = False, parse_form_data: 'bool' = False) -> 'bytes | str'
| This reads the buffered incoming data from the client into one
| bytes object. By default this is cached but that behavior can be
| changed by setting `cache` to `False`.
|
| Usually it's a bad idea to call this method without checking the
| content length first as a client could send dozens of megabytes or more
| to cause memory problems on the server.
|
| Note that if the form data was already parsed this method will not
| return anything as form data parsing does not cache the data like
| this method does. To implicitly invoke form data parsing function
| set `parse_form_data` to `True`. When this is done the return value
| of this method will be an empty string if the form parser handles
| the data. This generally is not necessary as if the whole data is
| cached (which is the default) the form parser will used the cached
| data to parse the form data. Please be generally aware of checking
| the content length first in any case before calling this method
| to avoid exhausting server memory.
|
| If `as_text` is set to `True` the return value will be a decoded
| string.
|
| .. versionadded:: 0.9
|
| get_json(self, force: 'bool' = False, silent: 'bool' = False, cache: 'bool' = True) -> 't.Any | None'
| Parse :attr:`data` as JSON.
|
| If the mimetype does not indicate JSON
| (:mimetype:`application/json`, see :attr:`is_json`), or parsing
| fails, :meth:`on_json_loading_failed` is called and
| its return value is used as the return value. By default this
| raises a 415 Unsupported Media Type resp.
|
| :param force: Ignore the mimetype and always try to parse JSON.
| :param silent: Silence mimetype and parsing errors, and
| return ``None`` instead.
| :param cache: Store the parsed JSON to return for subsequent
| calls.
|
| .. versionchanged:: 2.3
| Raise a 415 error instead of 400.
|
| .. versionchanged:: 2.1
| Raise a 400 error if the content type is incorrect.
|
| make_form_data_parser(self) -> 'FormDataParser'
| Creates the form data parser. Instantiates the
| :attr:`form_data_parser_class` with some parameters.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Class methods inherited from werkzeug.wrappers.request.Request:
|
| application(f: 't.Callable[[Request], WSGIApplication]') -> 'WSGIApplication'
| Decorate a function as responder that accepts the request as
| the last argument. This works like the :func:`responder`
| decorator but the function is passed the request object as the
| last argument and the request object will be closed
| automatically::
|
| @Request.application
| def my_wsgi_app(request):
| return Response('Hello World!')
|
| As of Werkzeug 0.14 HTTP exceptions are automatically caught and
| converted to responses instead of failing.
|
| :param f: the WSGI callable to decorate
| :return: a new WSGI callable
|
| from_values(*args: 't.Any', **kwargs: 't.Any') -> 'Request'
| Create a new request object based on the values provided. If
| environ is given missing values are filled from there. This method is
| useful for small scripts when you need to simulate a request from an URL.
| Do not use this method for unittesting, there is a full featured client
| object (:class:`Client`) that allows to create multipart requests,
| support for cookies etc.
|
| This accepts the same options as the
| :class:`~werkzeug.test.EnvironBuilder`.
|
| .. versionchanged:: 0.5
| This method now accepts the same arguments as
| :class:`~werkzeug.test.EnvironBuilder`. Because of this the
| `environ` parameter is now called `environ_overrides`.
|
| :return: request object
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.wrappers.request.Request:
|
| data
| The raw data read from :attr:`stream`. Will be empty if the request
| represents form data.
|
| To get the raw data even if it represents form data, use :meth:`get_data`.
|
| files
| :class:`~werkzeug.datastructures.MultiDict` object containing
| all uploaded files. Each key in :attr:`files` is the name from the
| ``<input type="file" name="">``. Each value in :attr:`files` is a
| Werkzeug :class:`~werkzeug.datastructures.FileStorage` object.
|
| It basically behaves like a standard file object you know from Python,
| with the difference that it also has a
| :meth:`~werkzeug.datastructures.FileStorage.save` function that can
| store the file on the filesystem.
|
| Note that :attr:`files` will only contain data if the request method was
| POST, PUT or PATCH and the ``<form>`` that posted to the request had
| ``enctype="multipart/form-data"``. It will be empty otherwise.
|
| See the :class:`~werkzeug.datastructures.MultiDict` /
| :class:`~werkzeug.datastructures.FileStorage` documentation for
| more details about the used data structure.
|
| form
| The form parameters. By default an
| :class:`~werkzeug.datastructures.ImmutableMultiDict`
| is returned from this function. This can be changed by setting
| :attr:`parameter_storage_class` to a different type. This might
| be necessary if the order of the form data is important.
|
| Please keep in mind that file uploads will not end up here, but instead
| in the :attr:`files` attribute.
|
| .. versionchanged:: 0.9
|
| Previous to Werkzeug 0.9 this would only contain form data for POST
| and PUT requests.
|
| json
| The parsed JSON data if :attr:`mimetype` indicates JSON
| (:mimetype:`application/json`, see :attr:`is_json`).
|
| Calls :meth:`get_json` with default arguments.
|
| If the request content type is not ``application/json``, this
| will raise a 415 Unsupported Media Type error.
|
| .. versionchanged:: 2.3
| Raise a 415 error instead of 400.
|
| .. versionchanged:: 2.1
| Raise a 400 error if the content type is incorrect.
|
| script_root
| Alias for :attr:`self.root_path`. ``environ["SCRIPT_NAME"]``
| without a trailing slash.
|
| stream
| The WSGI input stream, with safety checks. This stream can only be consumed
| once.
|
| Use :meth:`get_data` to get the full data as bytes or text. The :attr:`data`
| attribute will contain the full bytes only if they do not represent form data.
| The :attr:`form` attribute will contain the parsed form data in that case.
|
| Unlike :attr:`input_stream`, this stream guards against infinite streams or
| reading past :attr:`content_length` or :attr:`max_content_length`.
|
| If ``max_content_length`` is set, it can be enforced on streams if
| ``wsgi.input_terminated`` is set. Otherwise, an empty stream is returned.
|
| If the limit is reached before the underlying stream is exhausted (such as a
| file that is too large, or an infinite stream), the remaining contents of the
| stream cannot be read safely. Depending on how the server handles this, clients
| may show a "connection reset" failure instead of seeing the 413 response.
|
| .. versionchanged:: 2.3
| Check ``max_content_length`` preemptively and while reading.
|
| .. versionchanged:: 0.9
| The stream is always set (but may be consumed) even if form parsing was
| accessed first.
|
| url_root
| Alias for :attr:`root_url`. The URL with scheme, host, and
| root path. For example, ``https://example.com/app/``.
|
| values
| A :class:`werkzeug.datastructures.CombinedMultiDict` that
| combines :attr:`args` and :attr:`form`.
|
| For GET requests, only ``args`` are present, not ``form``.
|
| .. versionchanged:: 2.0
| For GET requests, only ``args`` are present, not ``form``.
|
| want_form_data_parsed
| ``True`` if the request method carries content. By default
| this is true if a ``Content-Type`` is sent.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.wrappers.request.Request:
|
| input_stream
| The raw WSGI input stream, without any safety checks.
|
| This is dangerous to use. It does not guard against infinite streams or reading
| past :attr:`content_length` or :attr:`max_content_length`.
|
| Use :attr:`stream` instead.
|
| is_multiprocess
| boolean that is `True` if the application is served by a
| WSGI server that spawns multiple processes.
|
| is_multithread
| boolean that is `True` if the application is served by a
| multithreaded WSGI server.
|
| is_run_once
| boolean that is `True` if the application will be
| executed only once in a process lifetime. This is the case for
| CGI for example, but it's not guaranteed that the execution only
| happens one time.
|
| remote_user
| If the server supports user authentication, and the
| script is protected, this attribute contains the username the
| user has authenticated as.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.wrappers.request.Request:
|
| form_data_parser_class = <class 'werkzeug.formparser.FormDataParser'>
| This class implements parsing of form data for Werkzeug. By itself
| it can parse multipart and url encoded form data. It can be subclassed
| and extended but for most mimetypes it is a better idea to use the
| untouched stream and expose it as separate attributes on a request
| object.
|
| :param stream_factory: An optional callable that returns a new read and
| writeable file descriptor. This callable works
| the same as :meth:`Response._get_file_stream`.
| :param max_form_memory_size: the maximum number of bytes to be accepted for
| in-memory stored form data. If the data
| exceeds the value specified an
| :exc:`~exceptions.RequestEntityTooLarge`
| exception is raised.
| :param max_content_length: If this is provided and the transmitted data
| is longer than this value an
| :exc:`~exceptions.RequestEntityTooLarge`
| exception is raised.
| :param cls: an optional dict class to use. If this is not specified
| or `None` the default :class:`MultiDict` is used.
| :param silent: If set to False parsing errors will not be caught.
| :param max_form_parts: The maximum number of multipart parts to be parsed. If this
| is exceeded, a :exc:`~exceptions.RequestEntityTooLarge` exception is raised.
|
| .. versionchanged:: 3.0
| The ``charset`` and ``errors`` parameters were removed.
|
| .. versionchanged:: 3.0
| The ``parse_functions`` attribute and ``get_parse_func`` methods were removed.
|
| .. versionchanged:: 2.2.3
| Added the ``max_form_parts`` parameter.
|
| .. versionadded:: 0.8
|
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.sansio.request.Request:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.sansio.request.Request:
|
| accept_charsets
| List of charsets this client supports as
| :class:`~werkzeug.datastructures.CharsetAccept` object.
|
| accept_encodings
| List of encodings this client accepts. Encodings in a HTTP term
| are compression encodings such as gzip. For charsets have a look at
| :attr:`accept_charset`.
|
| accept_languages
| List of languages this client accepts as
| :class:`~werkzeug.datastructures.LanguageAccept` object.
|
| .. versionchanged 0.5
| In previous versions this was a regular
| :class:`~werkzeug.datastructures.Accept` object.
|
| accept_mimetypes
| List of mimetypes this client supports as
| :class:`~werkzeug.datastructures.MIMEAccept` object.
|
| access_route
| If a forwarded header exists this is a list of all ip addresses
| from the client ip to the last proxy server.
|
| args
| The parsed URL parameters (the part in the URL after the question
| mark).
|
| By default an
| :class:`~werkzeug.datastructures.ImmutableMultiDict`
| is returned from this function. This can be changed by setting
| :attr:`parameter_storage_class` to a different type. This might
| be necessary if the order of the form data is important.
|
| .. versionchanged:: 2.3
| Invalid bytes remain percent encoded.
|
| authorization
| The ``Authorization`` header parsed into an :class:`.Authorization` object.
| ``None`` if the header is not present.
|
| .. versionchanged:: 2.3
| :class:`Authorization` is no longer a ``dict``. The ``token`` attribute
| was added for auth schemes that use a token instead of parameters.
|
| base_url
| Like :attr:`url` but without the query string.
|
| cache_control
| A :class:`~werkzeug.datastructures.RequestCacheControl` object
| for the incoming cache control headers.
|
| content_length
| The Content-Length entity-header field indicates the size of the
| entity-body in bytes or, in the case of the HEAD method, the size of
| the entity-body that would have been sent had the request been a
| GET.
|
| cookies
| A :class:`dict` with the contents of all cookies transmitted with
| the request.
|
| full_path
| Requested path, including the query string.
|
| host
| The host name the request was made to, including the port if
| it's non-standard. Validated with :attr:`trusted_hosts`.
|
| See :func:`.get_host` for a detailed explanation.
|
| host_url
| The request URL scheme and host only.
|
| if_match
| An object containing all the etags in the `If-Match` header.
|
| :rtype: :class:`~werkzeug.datastructures.ETags`
|
| if_modified_since
| The parsed `If-Modified-Since` header as a datetime object.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| if_none_match
| An object containing all the etags in the `If-None-Match` header.
|
| :rtype: :class:`~werkzeug.datastructures.ETags`
|
| if_range
| The parsed ``If-Range`` header.
|
| .. versionchanged:: 2.0
| ``IfRange.date`` is timezone-aware.
|
| .. versionadded:: 0.7
|
| if_unmodified_since
| The parsed `If-Unmodified-Since` header as a datetime object.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| is_json
| Check if the mimetype indicates JSON data, either
| :mimetype:`application/json` or :mimetype:`application/*+json`.
|
| is_secure
| ``True`` if the request was made with a secure protocol
| (HTTPS or WSS).
|
| mimetype
| Like :attr:`content_type`, but without parameters (eg, without
| charset, type etc.) and always lowercase. For example if the content
| type is ``text/HTML; charset=utf-8`` the mimetype would be
| ``'text/html'``.
|
| mimetype_params
| The mimetype parameters as dict. For example if the content
| type is ``text/html; charset=utf-8`` the params would be
| ``{'charset': 'utf-8'}``.
|
| pragma
| The Pragma general-header field is used to include
| implementation-specific directives that might apply to any recipient
| along the request/response chain. All pragma directives specify
| optional behavior from the viewpoint of the protocol; however, some
| systems MAY require that behavior be consistent with the directives.
|
| range
| The parsed `Range` header.
|
| .. versionadded:: 0.7
|
| :rtype: :class:`~werkzeug.datastructures.Range`
|
| root_url
| The request URL scheme, host, and root path. This is the root
| that the application is accessed from.
|
| url
| The full request URL with the scheme, host, root path, path,
| and query string.
|
| user_agent
| The user agent. Use ``user_agent.string`` to get the header
| value. Set :attr:`user_agent_class` to a subclass of
| :class:`~werkzeug.user_agent.UserAgent` to provide parsing for
| the other properties or other extended data.
|
| .. versionchanged:: 2.1
| The built-in parser was removed. Set ``user_agent_class`` to a ``UserAgent``
| subclass to parse data from the string.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.sansio.request.Request:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| access_control_request_headers
| Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set :attr:`~CORSResponseMixin.access_control_allow_headers` on the response to indicate which headers are allowed.
|
| access_control_request_method
| Sent with a preflight request to indicate which method will be used for the cross origin request. Set :attr:`~CORSResponseMixin.access_control_allow_methods` on the response to indicate which methods are allowed.
|
| content_encoding
| The Content-Encoding entity-header field is used as a
| modifier to the media-type. When present, its value indicates
| what additional content codings have been applied to the
| entity-body, and thus what decoding mechanisms must be applied
| in order to obtain the media-type referenced by the Content-Type
| header field.
|
| .. versionadded:: 0.9
|
| content_md5
| The Content-MD5 entity-header field, as defined in
| RFC 1864, is an MD5 digest of the entity-body for the purpose of
| providing an end-to-end message integrity check (MIC) of the
| entity-body. (Note: a MIC is good for detecting accidental
| modification of the entity-body in transit, but is not proof
| against malicious attacks.)
|
| .. versionadded:: 0.9
|
| content_type
| The Content-Type entity-header field indicates the media
| type of the entity-body sent to the recipient or, in the case of
| the HEAD method, the media type that would have been sent had
| the request been a GET.
|
| date
| The Date general-header field represents the date and
| time at which the message was originated, having the same
| semantics as orig-date in RFC 822.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| max_forwards
| The Max-Forwards request-header field provides a
| mechanism with the TRACE and OPTIONS methods to limit the number
| of proxies or gateways that can forward the request to the next
| inbound server.
|
| origin
| The host that the request originated from. Set :attr:`~CORSResponseMixin.access_control_allow_origin` on the response to indicate which origins are allowed.
|
| referrer
| The Referer[sic] request-header field allows the client
| to specify, for the server's benefit, the address (URI) of the
| resource from which the Request-URI was obtained (the
| "referrer", although the header field is misspelled).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.sansio.request.Request:
|
| dict_storage_class = <class 'werkzeug.datastructures.structures.Immuta...
| An immutable :class:`MultiDict`.
|
| .. versionadded:: 0.5
|
|
| list_storage_class = <class 'werkzeug.datastructures.structures.Immuta...
| An immutable :class:`list`.
|
| .. versionadded:: 0.5
|
| :private:
|
|
| parameter_storage_class = <class 'werkzeug.datastructures.structures.I...
| An immutable :class:`MultiDict`.
|
| .. versionadded:: 0.5
|
|
| trusted_hosts = None
|
| user_agent_class = <class 'werkzeug.user_agent.UserAgent'>
| Represents a parsed user agent header value.
|
| The default implementation does no parsing, only the :attr:`string`
| attribute is set. A subclass may parse the string to set the
| common attributes or expose other information. Set
| :attr:`werkzeug.wrappers.Request.user_agent_class` to use a
| subclass.
|
| :param string: The header value to parse.
|
| .. versionadded:: 2.0
| This replaces the previous ``useragents`` module, but does not
| provide a built-in parser.
flask.Response
Python Library Documentation: class Response in module flask.wrappers
class Response(werkzeug.wrappers.response.Response)
| Response(response: 't.Iterable[bytes] | bytes | t.Iterable[str] | str | None' = None, status: 'int | str | HTTPStatus | None' = None, headers: 't.Mapping[str, str | t.Iterable[str]] | t.Iterable[tuple[str, str]] | None' = None, mimetype: 'str | None' = None, content_type: 'str | None' = None, direct_passthrough: 'bool' = False) -> 'None'
|
| The response object that is used by default in Flask. Works like the
| response object from Werkzeug but is set to have an HTML mimetype by
| default. Quite often you don't have to create this object yourself because
| :meth:`~flask.Flask.make_response` will take care of that for you.
|
| If you want to replace the response object used you can subclass this and
| set :attr:`~flask.Flask.response_class` to your subclass.
|
| .. versionchanged:: 1.0
| JSON support is added to the response, like the request. This is useful
| when testing to get the test client response data as JSON.
|
| .. versionchanged:: 1.0
|
| Added :attr:`max_cookie_size`.
|
| Method resolution order:
| Response
| werkzeug.wrappers.response.Response
| werkzeug.sansio.response.Response
| builtins.object
|
| Readonly properties defined here:
|
| max_cookie_size
| Read-only view of the :data:`MAX_COOKIE_SIZE` config key.
|
| See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in
| Werkzeug's docs.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_mimetype': 'str | None'}
|
| autocorrect_location_header = False
|
| default_mimetype = 'text/html'
|
| json_module = <module 'flask.json' from 'C:\\Users\\Youse\\App...2\\Li...
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.wrappers.response.Response:
|
| __call__(self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 't.Iterable[bytes]'
| Process this response as WSGI application.
|
| :param environ: the WSGI environment.
| :param start_response: the response callable provided by the WSGI
| server.
| :return: an application iterator
|
| __enter__(self) -> 'Response'
|
| __exit__(self, exc_type, exc_value, tb)
|
| __init__(self, response: 't.Iterable[bytes] | bytes | t.Iterable[str] | str | None' = None, status: 'int | str | HTTPStatus | None' = None, headers: 't.Mapping[str, str | t.Iterable[str]] | t.Iterable[tuple[str, str]] | None' = None, mimetype: 'str | None' = None, content_type: 'str | None' = None, direct_passthrough: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_etag(self, overwrite: 'bool' = False, weak: 'bool' = False) -> 'None'
| Add an etag for the current response if there is none yet.
|
| .. versionchanged:: 2.0
| SHA-1 is used to generate the value. MD5 may not be
| available in some environments.
|
| calculate_content_length(self) -> 'int | None'
| Returns the content length if available or `None` otherwise.
|
| call_on_close(self, func: 't.Callable[[], t.Any]') -> 't.Callable[[], t.Any]'
| Adds a function to the internal list of functions that should
| be called as part of closing down the response. Since 0.7 this
| function also returns the function that was passed so that this
| can be used as a decorator.
|
| .. versionadded:: 0.6
|
| close(self) -> 'None'
| Close the wrapped response if possible. You can also use the object
| in a with statement which will automatically close it.
|
| .. versionadded:: 0.9
| Can now be used in a with statement.
|
| freeze(self) -> 'None'
| Make the response object ready to be pickled. Does the
| following:
|
| * Buffer the response into a list, ignoring
| :attr:`implicity_sequence_conversion` and
| :attr:`direct_passthrough`.
| * Set the ``Content-Length`` header.
| * Generate an ``ETag`` header if one is not already set.
|
| .. versionchanged:: 2.1
| Removed the ``no_etag`` parameter.
|
| .. versionchanged:: 2.0
| An ``ETag`` header is always added.
|
| .. versionchanged:: 0.6
| The ``Content-Length`` header is set.
|
| get_app_iter(self, environ: 'WSGIEnvironment') -> 't.Iterable[bytes]'
| Returns the application iterator for the given environ. Depending
| on the request method and the current status code the return value
| might be an empty response rather than the one from the response.
|
| If the request method is `HEAD` or the status code is in a range
| where the HTTP specification requires an empty response, an empty
| iterable is returned.
|
| .. versionadded:: 0.6
|
| :param environ: the WSGI environment of the request.
| :return: a response iterable.
|
| get_data(self, as_text: 'bool' = False) -> 'bytes | str'
| The string representation of the response body. Whenever you call
| this property the response iterable is encoded and flattened. This
| can lead to unwanted behavior if you stream big data.
|
| This behavior can be disabled by setting
| :attr:`implicit_sequence_conversion` to `False`.
|
| If `as_text` is set to `True` the return value will be a decoded
| string.
|
| .. versionadded:: 0.9
|
| get_json(self, force: 'bool' = False, silent: 'bool' = False) -> 't.Any | None'
| Parse :attr:`data` as JSON. Useful during testing.
|
| If the mimetype does not indicate JSON
| (:mimetype:`application/json`, see :attr:`is_json`), this
| returns ``None``.
|
| Unlike :meth:`Request.get_json`, the result is not cached.
|
| :param force: Ignore the mimetype and always try to parse JSON.
| :param silent: Silence parsing errors and return ``None``
| instead.
|
| get_wsgi_headers(self, environ: 'WSGIEnvironment') -> 'Headers'
| This is automatically called right before the response is started
| and returns headers modified for the given environment. It returns a
| copy of the headers from the response with some modifications applied
| if necessary.
|
| For example the location header (if present) is joined with the root
| URL of the environment. Also the content length is automatically set
| to zero here for certain status codes.
|
| .. versionchanged:: 0.6
| Previously that function was called `fix_headers` and modified
| the response object in place. Also since 0.6, IRIs in location
| and content-location headers are handled properly.
|
| Also starting with 0.6, Werkzeug will attempt to set the content
| length if it is able to figure it out on its own. This is the
| case if all the strings in the response iterable are already
| encoded and the iterable is buffered.
|
| :param environ: the WSGI environment of the request.
| :return: returns a new :class:`~werkzeug.datastructures.Headers`
| object.
|
| get_wsgi_response(self, environ: 'WSGIEnvironment') -> 'tuple[t.Iterable[bytes], str, list[tuple[str, str]]]'
| Returns the final WSGI response as tuple. The first item in
| the tuple is the application iterator, the second the status and
| the third the list of headers. The response returned is created
| specially for the given environment. For example if the request
| method in the WSGI environment is ``'HEAD'`` the response will
| be empty and only the headers and status code will be present.
|
| .. versionadded:: 0.6
|
| :param environ: the WSGI environment of the request.
| :return: an ``(app_iter, status, headers)`` tuple.
|
| iter_encoded(self) -> 't.Iterator[bytes]'
| Iter the response encoded with the encoding of the response.
| If the response object is invoked as WSGI application the return
| value of this method is used as application iterator unless
| :attr:`direct_passthrough` was activated.
|
| make_conditional(self, request_or_environ: 'WSGIEnvironment | Request', accept_ranges: 'bool | str' = False, complete_length: 'int | None' = None) -> 'Response'
| Make the response conditional to the request. This method works
| best if an etag was defined for the response already. The `add_etag`
| method can be used to do that. If called without etag just the date
| header is set.
|
| This does nothing if the request method in the request or environ is
| anything but GET or HEAD.
|
| For optimal performance when handling range requests, it's recommended
| that your response data object implements `seekable`, `seek` and `tell`
| methods as described by :py:class:`io.IOBase`. Objects returned by
| :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.
|
| It does not remove the body of the response because that's something
| the :meth:`__call__` function does for us automatically.
|
| Returns self so that you can do ``return resp.make_conditional(req)``
| but modifies the object in-place.
|
| :param request_or_environ: a request object or WSGI environment to be
| used to make the response conditional
| against.
| :param accept_ranges: This parameter dictates the value of
| `Accept-Ranges` header. If ``False`` (default),
| the header is not set. If ``True``, it will be set
| to ``"bytes"``. If it's a string, it will use this
| value.
| :param complete_length: Will be used only in valid Range Requests.
| It will set `Content-Range` complete length
| value and compute `Content-Length` real value.
| This parameter is mandatory for successful
| Range Requests completion.
| :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
| if `Range` header could not be parsed or satisfied.
|
| .. versionchangedd: 3.2
| Adds the ``Accept-Ranges`` header if ``accept_ranges`` is passed,
| even if this is not a satisfiable range request.
|
| .. versionchanged:: 2.0
| Range processing is skipped if length is 0 instead of
| raising a 416 Range Not Satisfiable error.
|
| make_sequence(self) -> 'None'
| Converts the response iterator in a list. By default this happens
| automatically if required. If `implicit_sequence_conversion` is
| disabled, this method is not automatically called and some properties
| might raise exceptions. This also encodes all the items.
|
| .. versionadded:: 0.6
|
| set_data(self, value: 'bytes | str') -> 'None'
| Sets a new string as response. The value must be a string or
| bytes. If a string is set it's encoded to the charset of the
| response (utf-8 by default).
|
| .. versionadded:: 0.9
|
| ----------------------------------------------------------------------
| Class methods inherited from werkzeug.wrappers.response.Response:
|
| force_type(response: 'Response', environ: 'WSGIEnvironment | None' = None) -> 'Response'
| Enforce that the WSGI response is a response object of the current
| type. Werkzeug will use the :class:`Response` internally in many
| situations like the exceptions. If you call :meth:`get_response` on an
| exception you will get back a regular :class:`Response` object, even
| if you are using a custom subclass.
|
| This method can enforce a given response type, and it will also
| convert arbitrary WSGI callables into response objects if an environ
| is provided::
|
| # convert a Werkzeug response object into an instance of the
| # MyResponseClass subclass.
| response = MyResponseClass.force_type(response)
|
| # convert any WSGI application into a response object
| response = MyResponseClass.force_type(response, environ)
|
| This is especially useful if you want to post-process responses in
| the main dispatcher and use functionality provided by your subclass.
|
| Keep in mind that this will modify response objects in place if
| possible!
|
| :param response: a response object or wsgi application.
| :param environ: a WSGI environment object.
| :return: a response object.
|
| from_app(app: 'WSGIApplication', environ: 'WSGIEnvironment', buffered: 'bool' = False) -> 'Response'
| Create a new response object from an application output. This
| works best if you pass it an application that returns a generator all
| the time. Sometimes applications may use the `write()` callable
| returned by the `start_response` function. This tries to resolve such
| edge cases automatically. But if you don't get the expected output
| you should set `buffered` to `True` which enforces buffering.
|
| :param app: the WSGI application to execute.
| :param environ: the WSGI environment to execute against.
| :param buffered: set to `True` to enforce buffering.
| :return: a response object.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.wrappers.response.Response:
|
| is_sequence
| If the iterator is buffered, this property will be `True`. A
| response object will consider an iterator to be buffered if the
| response attribute is a list or tuple.
|
| .. versionadded:: 0.6
|
| is_streamed
| If the response is streamed (the response is not an iterable with
| a length information) this property is `True`. In this case streamed
| means that there is no information about the number of iterations.
| This is usually `True` if a generator is passed to the response object.
|
| This is useful for checking before applying some sort of post
| filtering that should not take place for streamed responses.
|
| json
| The parsed JSON data if :attr:`mimetype` indicates JSON
| (:mimetype:`application/json`, see :attr:`is_json`).
|
| Calls :meth:`get_json` with default arguments.
|
| stream
| The response iterable as write-only stream.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.wrappers.response.Response:
|
| data
| A descriptor that calls :meth:`get_data` and :meth:`set_data`.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.wrappers.response.Response:
|
| automatically_set_content_length = True
|
| implicit_sequence_conversion = True
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.sansio.response.Response:
|
| delete_cookie(self, key: 'str', path: 'str | None' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: 'str | None' = None, partitioned: 'bool' = False) -> 'None'
| Delete a cookie. Fails silently if key doesn't exist.
|
| :param key: the key (name) of the cookie to be deleted.
| :param path: if the cookie that should be deleted was limited to a
| path, the path has to be defined here.
| :param domain: if the cookie that should be deleted was limited to a
| domain, that domain has to be defined here.
| :param secure: If ``True``, the cookie will only be available
| via HTTPS.
| :param httponly: Disallow JavaScript access to the cookie.
| :param samesite: Limit the scope of the cookie to only be
| attached to requests that are "same-site".
| :param partitioned: If ``True``, the cookie will be partitioned.
|
| get_etag(self) -> 'tuple[str, bool] | tuple[None, None]'
| Return a tuple in the form ``(etag, is_weak)``. If there is no
| ETag the return value is ``(None, None)``.
|
| set_cookie(self, key: 'str', value: 'str' = '', max_age: 'timedelta | int | None' = None, expires: 'str | datetime | int | float | None' = None, path: 'str | None' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: 'str | None' = None, partitioned: 'bool' = False) -> 'None'
| Sets a cookie.
|
| A warning is raised if the size of the cookie header exceeds
| :attr:`max_cookie_size`, but the header will still be set.
|
| :param key: the key (name) of the cookie to be set.
| :param value: the value of the cookie.
| :param max_age: should be a number of seconds, or `None` (default) if
| the cookie should last only as long as the client's
| browser session.
| :param expires: should be a `datetime` object or UNIX timestamp.
| :param path: limits the cookie to a given path, per default it will
| span the whole domain.
| :param domain: if you want to set a cross-domain cookie. For example,
| ``domain="example.com"`` will set a cookie that is
| readable by the domain ``www.example.com``,
| ``foo.example.com`` etc. Otherwise, a cookie will only
| be readable by the domain that set it.
| :param secure: If ``True``, the cookie will only be available
| via HTTPS.
| :param httponly: Disallow JavaScript access to the cookie.
| :param samesite: Limit the scope of the cookie to only be
| attached to requests that are "same-site".
| :param partitioned: If ``True``, the cookie will be partitioned.
|
| .. versionchanged:: 3.1
| The ``partitioned`` parameter was added.
|
| set_etag(self, etag: 'str', weak: 'bool' = False) -> 'None'
| Set the etag, and override the old one if there was one.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.sansio.response.Response:
|
| cache_control
| The Cache-Control general-header field is used to specify
| directives that MUST be obeyed by all caching mechanisms along the
| request/response chain.
|
| is_json
| Check if the mimetype indicates JSON data, either
| :mimetype:`application/json` or :mimetype:`application/*+json`.
|
| mimetype_params
| The mimetype parameters as dict. For example if the
| content type is ``text/html; charset=utf-8`` the params would be
| ``{'charset': 'utf-8'}``.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.sansio.response.Response:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| accept_ranges
| The `Accept-Ranges` header. Even though the name would
| indicate that multiple values are supported, it must be one
| string token only.
|
| The values ``'bytes'`` and ``'none'`` are common.
|
| .. versionadded:: 0.7
|
| access_control_allow_credentials
| Whether credentials can be shared by the browser to
| JavaScript code. As part of the preflight request it indicates
| whether credentials can be used on the cross origin request.
|
| access_control_allow_headers
| Which headers can be sent with the cross origin request.
|
| access_control_allow_methods
| Which methods can be used for the cross origin request.
|
| access_control_allow_origin
| The origin or '*' for any origin that may make cross origin requests.
|
| access_control_expose_headers
| Which headers can be shared by the browser to JavaScript code.
|
| access_control_max_age
| The maximum age in seconds the access control settings can be cached for.
|
| age
| The Age response-header field conveys the sender's
| estimate of the amount of time since the response (or its
| revalidation) was generated at the origin server.
|
| Age values are non-negative decimal integers, representing time
| in seconds.
|
| allow
| The Allow entity-header field lists the set of methods
| supported by the resource identified by the Request-URI. The
| purpose of this field is strictly to inform the recipient of
| valid methods associated with the resource. An Allow header
| field MUST be present in a 405 (Method Not Allowed)
| response.
|
| content_encoding
| The Content-Encoding entity-header field is used as a
| modifier to the media-type. When present, its value indicates
| what additional content codings have been applied to the
| entity-body, and thus what decoding mechanisms must be applied
| in order to obtain the media-type referenced by the Content-Type
| header field.
|
| content_language
| The Content-Language entity-header field describes the
| natural language(s) of the intended audience for the enclosed
| entity. Note that this might not be equivalent to all the
| languages used within the entity-body.
|
| content_length
| The Content-Length entity-header field indicates the size
| of the entity-body, in decimal number of OCTETs, sent to the
| recipient or, in the case of the HEAD method, the size of the
| entity-body that would have been sent had the request been a
| GET.
|
| content_location
| The Content-Location entity-header field MAY be used to
| supply the resource location for the entity enclosed in the
| message when that entity is accessible from a location separate
| from the requested resource's URI.
|
| content_md5
| The Content-MD5 entity-header field, as defined in
| RFC 1864, is an MD5 digest of the entity-body for the purpose of
| providing an end-to-end message integrity check (MIC) of the
| entity-body. (Note: a MIC is good for detecting accidental
| modification of the entity-body in transit, but is not proof
| against malicious attacks.)
|
| content_range
| The ``Content-Range`` header as a
| :class:`~werkzeug.datastructures.ContentRange` object. Available
| even if the header is not set.
|
| .. versionadded:: 0.7
|
| content_security_policy
| The ``Content-Security-Policy`` header as a
| :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
| even if the header is not set.
|
| The Content-Security-Policy header adds an additional layer of
| security to help detect and mitigate certain types of attacks.
|
| content_security_policy_report_only
| The ``Content-Security-policy-report-only`` header as a
| :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
| even if the header is not set.
|
| The Content-Security-Policy-Report-Only header adds a csp policy
| that is not enforced but is reported thereby helping detect
| certain types of attacks.
|
| content_type
| The Content-Type entity-header field indicates the media
| type of the entity-body sent to the recipient or, in the case of
| the HEAD method, the media type that would have been sent had
| the request been a GET.
|
| cross_origin_embedder_policy
| Prevents a document from loading any cross-origin resources that do not
| explicitly grant the document permission. Values must be a member of the
| :class:`werkzeug.http.COEP` enum.
|
| cross_origin_opener_policy
| Allows control over sharing of browsing context group with cross-origin
| documents. Values must be a member of the :class:`werkzeug.http.COOP` enum.
|
| date
| The Date general-header field represents the date and
| time at which the message was originated, having the same
| semantics as orig-date in RFC 822.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| expires
| The Expires entity-header field gives the date/time after
| which the response is considered stale. A stale cache entry may
| not normally be returned by a cache.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| last_modified
| The Last-Modified entity-header field indicates the date
| and time at which the origin server believes the variant was
| last modified.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| location
| The Location response-header field is used to redirect
| the recipient to a location other than the Request-URI for
| completion of the request or identification of a new
| resource.
|
| mimetype
| The mimetype (content type without charset etc.)
|
| retry_after
| The Retry-After response-header field can be used with a
| 503 (Service Unavailable) response to indicate how long the
| service is expected to be unavailable to the requesting client.
|
| Time in seconds until expiration or date.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| status
| The HTTP status code as a string.
|
| status_code
| The HTTP status code as a number.
|
| vary
| The Vary field value indicates the set of request-header
| fields that fully determines, while the response is fresh,
| whether a cache is permitted to use the response to reply to a
| subsequent request without revalidation.
|
| www_authenticate
| The ``WWW-Authenticate`` header parsed into a :class:`.WWWAuthenticate`
| object. Modifying the object will modify the header value.
|
| This header is not set by default. To set this header, assign an instance of
| :class:`.WWWAuthenticate` to this attribute.
|
| .. code-block:: python
|
| response.www_authenticate = WWWAuthenticate(
| "basic", {"realm": "Authentication Required"}
| )
|
| Multiple values for this header can be sent to give the client multiple options.
| Assign a list to set multiple headers. However, modifying the items in the list
| will not automatically update the header values, and accessing this attribute
| will only ever return the first value.
|
| To unset this header, assign ``None`` or use ``del``.
|
| .. versionchanged:: 2.3
| This attribute can be assigned to set the header. A list can be assigned
| to set multiple header values. Use ``del`` to unset the header.
|
| .. versionchanged:: 2.3
| :class:`WWWAuthenticate` is no longer a ``dict``. The ``token`` attribute
| was added for auth challenges that use a token instead of parameters.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.sansio.response.Response:
|
| default_status = 200
flask.abort
Python Library Documentation: function abort in module flask.helpers
abort(code: 'int | BaseResponse', *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given
status code.
If :data:`~flask.current_app` is available, it will call its
:attr:`~flask.Flask.aborter` object, otherwise it will use
:func:`werkzeug.exceptions.abort`.
:param code: The status code for the exception, which must be
registered in ``app.aborter``.
:param args: Passed to the exception.
:param kwargs: Passed to the exception.
.. versionadded:: 2.2
Calls ``current_app.aborter`` if available instead of always
using Werkzeug's default ``abort``.
flask.after_this_request
Python Library Documentation: function after_this_request in module flask.ctx
after_this_request(f: 'ft.AfterRequestCallable[t.Any]') -> 'ft.AfterRequestCallable[t.Any]'
Executes a function after this request. This is useful to modify
response objects. The function is passed the response object and has
to return the same or a new one.
Example::
@app.route('/')
def index():
@after_this_request
def add_header(response):
response.headers['X-Foo'] = 'Parachute'
return response
return 'Hello World!'
This is more useful if a function other than the view function wants to
modify a response. For instance think of a decorator that wants to add
some headers without converting the return value into a response object.
.. versionadded:: 0.9
flask.annotations
Python Library Documentation: _Feature in module __future__ object class _Feature(builtins.object) | _Feature(optionalRelease, mandatoryRelease, compiler_flag) | | Methods defined here: | | __init__(self, optionalRelease, mandatoryRelease, compiler_flag) | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) | Return repr(self). | | getMandatoryRelease(self) | Return release in which this feature will become mandatory. | | This is a 5-tuple, of the same form as sys.version_info, or, if | the feature was dropped, or the release date is undetermined, is None. | | getOptionalRelease(self) | Return first release in which this feature was recognized. | | This is a 5-tuple, of the same form as sys.version_info. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
flask.app
Python Library Documentation: module flask.app in flask
NAME
flask.app
CLASSES
flask.sansio.app.App(flask.sansio.scaffold.Scaffold)
Flask
class Flask(flask.sansio.app.App)
| Flask(import_name: 'str', static_url_path: 'str | None' = None, static_folder: 'str | os.PathLike[str] | None' = 'static', static_host: 'str | None' = None, host_matching: 'bool' = False, subdomain_matching: 'bool' = False, template_folder: 'str | os.PathLike[str] | None' = 'templates', instance_path: 'str | None' = None, instance_relative_config: 'bool' = False, root_path: 'str | None' = None)
|
| The flask object implements a WSGI application and acts as the central
| object. It is passed the name of the module or package of the
| application. Once it is created it will act as a central registry for
| the view functions, the URL rules, template configuration and much more.
|
| The name of the package is used to resolve resources from inside the
| package or the folder the module is contained in depending on if the
| package parameter resolves to an actual python package (a folder with
| an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
|
| For more information about resource loading, see :func:`open_resource`.
|
| Usually you create a :class:`Flask` instance in your main module or
| in the :file:`__init__.py` file of your package like this::
|
| from flask import Flask
| app = Flask(__name__)
|
| .. admonition:: About the First Parameter
|
| The idea of the first parameter is to give Flask an idea of what
| belongs to your application. This name is used to find resources
| on the filesystem, can be used by extensions to improve debugging
| information and a lot more.
|
| So it's important what you provide there. If you are using a single
| module, `__name__` is always the correct value. If you however are
| using a package, it's usually recommended to hardcode the name of
| your package there.
|
| For example if your application is defined in :file:`yourapplication/app.py`
| you should create it with one of the two versions below::
|
| app = Flask('yourapplication')
| app = Flask(__name__.split('.')[0])
|
| Why is that? The application will work even with `__name__`, thanks
| to how resources are looked up. However it will make debugging more
| painful. Certain extensions can make assumptions based on the
| import name of your application. For example the Flask-SQLAlchemy
| extension will look for the code in your application that triggered
| an SQL query in debug mode. If the import name is not properly set
| up, that debugging information is lost. (For example it would only
| pick up SQL queries in `yourapplication.app` and not
| `yourapplication.views.frontend`)
|
| .. versionadded:: 0.7
| The `static_url_path`, `static_folder`, and `template_folder`
| parameters were added.
|
| .. versionadded:: 0.8
| The `instance_path` and `instance_relative_config` parameters were
| added.
|
| .. versionadded:: 0.11
| The `root_path` parameter was added.
|
| .. versionadded:: 1.0
| The ``host_matching`` and ``static_host`` parameters were added.
|
| .. versionadded:: 1.0
| The ``subdomain_matching`` parameter was added. Subdomain
| matching needs to be enabled manually now. Setting
| :data:`SERVER_NAME` does not implicitly enable it.
|
| :param import_name: the name of the application package
| :param static_url_path: can be used to specify a different path for the
| static files on the web. Defaults to the name
| of the `static_folder` folder.
| :param static_folder: The folder with static files that is served at
| ``static_url_path``. Relative to the application ``root_path``
| or an absolute path. Defaults to ``'static'``.
| :param static_host: the host to use when adding the static route.
| Defaults to None. Required when using ``host_matching=True``
| with a ``static_folder`` configured.
| :param host_matching: set ``url_map.host_matching`` attribute.
| Defaults to False.
| :param subdomain_matching: consider the subdomain relative to
| :data:`SERVER_NAME` when matching routes. Defaults to False.
| :param template_folder: the folder that contains the templates that should
| be used by the application. Defaults to
| ``'templates'`` folder in the root path of the
| application.
| :param instance_path: An alternative instance path for the application.
| By default the folder ``'instance'`` next to the
| package or module is assumed to be the instance
| path.
| :param instance_relative_config: if set to ``True`` relative filenames
| for loading the config are assumed to
| be relative to the instance path instead
| of the application root.
| :param root_path: The path to the root of the application files.
| This should only be set manually when it can't be detected
| automatically, such as for namespace packages.
|
| Method resolution order:
| Flask
| flask.sansio.app.App
| flask.sansio.scaffold.Scaffold
| builtins.object
|
| Methods defined here:
|
| __call__(self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 'cabc.Iterable[bytes]'
| The WSGI server calls the Flask application object as the
| WSGI application. This calls :meth:`wsgi_app`, which can be
| wrapped to apply middleware.
|
| __init__(self, import_name: 'str', static_url_path: 'str | None' = None, static_folder: 'str | os.PathLike[str] | None' = 'static', static_host: 'str | None' = None, host_matching: 'bool' = False, subdomain_matching: 'bool' = False, template_folder: 'str | os.PathLike[str] | None' = 'templates', instance_path: 'str | None' = None, instance_relative_config: 'bool' = False, root_path: 'str | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| app_context(self) -> 'AppContext'
| Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
| block to push the context, which will make :data:`current_app`
| point at this application.
|
| An application context is automatically pushed by
| :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
| when handling a request, and when running a CLI command. Use
| this to manually create a context outside of these situations.
|
| ::
|
| with app.app_context():
| init_db()
|
| See :doc:`/appcontext`.
|
| .. versionadded:: 0.9
|
| async_to_sync(self, func: 't.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]') -> 't.Callable[..., t.Any]'
| Return a sync function that will run the coroutine function.
|
| .. code-block:: python
|
| result = app.async_to_sync(func)(*args, **kwargs)
|
| Override this method to change how the app converts async code
| to be synchronously callable.
|
| .. versionadded:: 2.0
|
| create_jinja_environment(self) -> 'Environment'
| Create the Jinja environment based on :attr:`jinja_options`
| and the various Jinja-related methods of the app. Changing
| :attr:`jinja_options` after this will have no effect. Also adds
| Flask-related globals and filters to the environment.
|
| .. versionchanged:: 0.11
| ``Environment.auto_reload`` set in accordance with
| ``TEMPLATES_AUTO_RELOAD`` configuration option.
|
| .. versionadded:: 0.5
|
| create_url_adapter(self, request: 'Request | None') -> 'MapAdapter | None'
| Creates a URL adapter for the given request. The URL adapter
| is created at a point where the request context is not yet set
| up so the request is passed explicitly.
|
| .. versionchanged:: 3.1
| If :data:`SERVER_NAME` is set, it does not restrict requests to
| only that domain, for both ``subdomain_matching`` and
| ``host_matching``.
|
| .. versionchanged:: 1.0
| :data:`SERVER_NAME` no longer implicitly enables subdomain
| matching. Use :attr:`subdomain_matching` instead.
|
| .. versionchanged:: 0.9
| This can be called outside a request when the URL adapter is created
| for an application context.
|
| .. versionadded:: 0.6
|
| dispatch_request(self) -> 'ft.ResponseReturnValue'
| Does the request dispatching. Matches the URL and returns the
| return value of the view or error handler. This does not have to
| be a response object. In order to convert the return value to a
| proper response object, call :func:`make_response`.
|
| .. versionchanged:: 0.7
| This no longer does the exception handling, this code was
| moved to the new :meth:`full_dispatch_request`.
|
| do_teardown_appcontext(self, exc: 'BaseException | None' = <object object at 0x00000232059594F0>) -> 'None'
| Called right before the application context is popped.
|
| When handling a request, the application context is popped
| after the request context. See :meth:`do_teardown_request`.
|
| This calls all functions decorated with
| :meth:`teardown_appcontext`. Then the
| :data:`appcontext_tearing_down` signal is sent.
|
| This is called by
| :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
|
| .. versionadded:: 0.9
|
| do_teardown_request(self, exc: 'BaseException | None' = <object object at 0x00000232059594F0>) -> 'None'
| Called after the request is dispatched and the response is
| returned, right before the request context is popped.
|
| This calls all functions decorated with
| :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
| if a blueprint handled the request. Finally, the
| :data:`request_tearing_down` signal is sent.
|
| This is called by
| :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
| which may be delayed during testing to maintain access to
| resources.
|
| :param exc: An unhandled exception raised while dispatching the
| request. Detected from the current exception information if
| not passed. Passed to each teardown function.
|
| .. versionchanged:: 0.9
| Added the ``exc`` argument.
|
| ensure_sync(self, func: 't.Callable[..., t.Any]') -> 't.Callable[..., t.Any]'
| Ensure that the function is synchronous for WSGI workers.
| Plain ``def`` functions are returned as-is. ``async def``
| functions are wrapped to run and wait for the response.
|
| Override this method to change how the app runs async views.
|
| .. versionadded:: 2.0
|
| finalize_request(self, rv: 'ft.ResponseReturnValue | HTTPException', from_error_handler: 'bool' = False) -> 'Response'
| Given the return value from a view function this finalizes
| the request by converting it into a response and invoking the
| postprocessing functions. This is invoked for both normal
| request dispatching as well as error handlers.
|
| Because this means that it might be called as a result of a
| failure a special safe mode is available which can be enabled
| with the `from_error_handler` flag. If enabled, failures in
| response processing will be logged and otherwise ignored.
|
| :internal:
|
| full_dispatch_request(self) -> 'Response'
| Dispatches the request and on top of that performs request
| pre and postprocessing as well as HTTP exception catching and
| error handling.
|
| .. versionadded:: 0.7
|
| get_send_file_max_age(self, filename: 'str | None') -> 'int | None'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionchanged:: 2.0
| The default configuration is ``None`` instead of 12 hours.
|
| .. versionadded:: 0.9
|
| handle_exception(self, e: 'Exception') -> 'Response'
| Handle an exception that did not have an error handler
| associated with it, or that was raised from an error handler.
| This always causes a 500 ``InternalServerError``.
|
| Always sends the :data:`got_request_exception` signal.
|
| If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug
| mode, the error will be re-raised so that the debugger can
| display it. Otherwise, the original exception is logged, and
| an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
|
| If an error handler is registered for ``InternalServerError`` or
| ``500``, it will be used. For consistency, the handler will
| always receive the ``InternalServerError``. The original
| unhandled exception is available as ``e.original_exception``.
|
| .. versionchanged:: 1.1.0
| Always passes the ``InternalServerError`` instance to the
| handler, setting ``original_exception`` to the unhandled
| error.
|
| .. versionchanged:: 1.1.0
| ``after_request`` functions and other finalization is done
| even for the default 500 response when there is no handler.
|
| .. versionadded:: 0.3
|
| handle_http_exception(self, e: 'HTTPException') -> 'HTTPException | ft.ResponseReturnValue'
| Handles an HTTP exception. By default this will invoke the
| registered error handlers and fall back to returning the
| exception as response.
|
| .. versionchanged:: 1.0.3
| ``RoutingException``, used internally for actions such as
| slash redirects during routing, is not passed to error
| handlers.
|
| .. versionchanged:: 1.0
| Exceptions are looked up by code *and* by MRO, so
| ``HTTPException`` subclasses can be handled with a catch-all
| handler for the base ``HTTPException``.
|
| .. versionadded:: 0.3
|
| handle_user_exception(self, e: 'Exception') -> 'HTTPException | ft.ResponseReturnValue'
| This method is called whenever an exception occurs that
| should be handled. A special case is :class:`~werkzeug
| .exceptions.HTTPException` which is forwarded to the
| :meth:`handle_http_exception` method. This function will either
| return a response value or reraise the exception with the same
| traceback.
|
| .. versionchanged:: 1.0
| Key errors raised from request data like ``form`` show the
| bad key in debug mode rather than a generic bad request
| message.
|
| .. versionadded:: 0.7
|
| log_exception(self, exc_info: 'tuple[type, BaseException, TracebackType] | tuple[None, None, None]') -> 'None'
| Logs an exception. This is called by :meth:`handle_exception`
| if debugging is disabled and right before the handler is called.
| The default implementation logs the exception as error on the
| :attr:`logger`.
|
| .. versionadded:: 0.8
|
| make_default_options_response(self) -> 'Response'
| This method is called to create the default ``OPTIONS`` response.
| This can be changed through subclassing to change the default
| behavior of ``OPTIONS`` responses.
|
| .. versionadded:: 0.7
|
| make_response(self, rv: 'ft.ResponseReturnValue') -> 'Response'
| Convert the return value from a view function to an instance of
| :attr:`response_class`.
|
| :param rv: the return value from the view function. The view function
| must return a response. Returning ``None``, or the view ending
| without returning, is not allowed. The following types are allowed
| for ``view_rv``:
|
| ``str``
| A response object is created with the string encoded to UTF-8
| as the body.
|
| ``bytes``
| A response object is created with the bytes as the body.
|
| ``dict``
| A dictionary that will be jsonify'd before being returned.
|
| ``list``
| A list that will be jsonify'd before being returned.
|
| ``generator`` or ``iterator``
| A generator that returns ``str`` or ``bytes`` to be
| streamed as the response.
|
| ``tuple``
| Either ``(body, status, headers)``, ``(body, status)``, or
| ``(body, headers)``, where ``body`` is any of the other types
| allowed here, ``status`` is a string or an integer, and
| ``headers`` is a dictionary or a list of ``(key, value)``
| tuples. If ``body`` is a :attr:`response_class` instance,
| ``status`` overwrites the exiting value and ``headers`` are
| extended.
|
| :attr:`response_class`
| The object is returned unchanged.
|
| other :class:`~werkzeug.wrappers.Response` class
| The object is coerced to :attr:`response_class`.
|
| :func:`callable`
| The function is called as a WSGI application. The result is
| used to create a response object.
|
| .. versionchanged:: 2.2
| A generator will be converted to a streaming response.
| A list will be converted to a JSON response.
|
| .. versionchanged:: 1.1
| A dict will be converted to a JSON response.
|
| .. versionchanged:: 0.9
| Previously a tuple was interpreted as the arguments for the
| response object.
|
| make_shell_context(self) -> 'dict[str, t.Any]'
| Returns the shell context for an interactive shell for this
| application. This runs all the registered shell context
| processors.
|
| .. versionadded:: 0.11
|
| open_instance_resource(self, resource: 'str', mode: 'str' = 'rb', encoding: 'str | None' = 'utf-8') -> 't.IO[t.AnyStr]'
| Open a resource file relative to the application's instance folder
| :attr:`instance_path`. Unlike :meth:`open_resource`, files in the
| instance folder can be opened for writing.
|
| :param resource: Path to the resource relative to :attr:`instance_path`.
| :param mode: Open the file in this mode.
| :param encoding: Open the file with this encoding when opening in text
| mode. This is ignored when opening in binary mode.
|
| .. versionchanged:: 3.1
| Added the ``encoding`` parameter.
|
| open_resource(self, resource: 'str', mode: 'str' = 'rb', encoding: 'str | None' = None) -> 't.IO[t.AnyStr]'
| 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"``.
| :param encoding: Open the file with this encoding when opening in text
| mode. This is ignored when opening in binary mode.
|
| .. versionchanged:: 3.1
| Added the ``encoding`` parameter.
|
| preprocess_request(self) -> 'ft.ResponseReturnValue | None'
| Called before the request is dispatched. Calls
| :attr:`url_value_preprocessors` registered with the app and the
| current blueprint (if any). Then calls :attr:`before_request_funcs`
| registered with the app and the blueprint.
|
| If any :meth:`before_request` handler 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.
|
| process_response(self, response: 'Response') -> 'Response'
| Can be overridden in order to modify the response object
| before it's sent to the WSGI server. By default this will
| call all the :meth:`after_request` decorated functions.
|
| .. versionchanged:: 0.5
| As of Flask 0.5 the functions registered for after request
| execution are called in reverse order of registration.
|
| :param response: a :attr:`response_class` object.
| :return: a new response object or the same, has to be an
| instance of :attr:`response_class`.
|
| raise_routing_exception(self, request: 'Request') -> 't.NoReturn'
| Intercept routing exceptions and possibly do something else.
|
| In debug mode, intercept a routing redirect and replace it with
| an error if the body will be discarded.
|
| With modern Werkzeug this shouldn't occur, since it now uses a
| 308 status which tells the browser to resend the method and
| body.
|
| .. versionchanged:: 2.1
| Don't intercept 307 and 308 redirects.
|
| :meta private:
| :internal:
|
| request_context(self, environ: 'WSGIEnvironment') -> 'RequestContext'
| Create a :class:`~flask.ctx.RequestContext` representing a
| WSGI environment. Use a ``with`` block to push the context,
| which will make :data:`request` point at this request.
|
| See :doc:`/reqcontext`.
|
| Typically you should not call this from your own code. A request
| context is automatically pushed by the :meth:`wsgi_app` when
| handling a request. Use :meth:`test_request_context` to create
| an environment and context instead of this method.
|
| :param environ: a WSGI environment
|
| run(self, host: 'str | None' = None, port: 'int | None' = None, debug: 'bool | None' = None, load_dotenv: 'bool' = True, **options: 't.Any') -> 'None'
| Runs the application on a local development server.
|
| Do not use ``run()`` in a production setting. It is not intended to
| meet security and performance requirements for a production server.
| Instead, see :doc:`/deploying/index` for WSGI server recommendations.
|
| If the :attr:`debug` flag is set the server will automatically reload
| for code changes and show a debugger in case an exception happened.
|
| If you want to run the application in debug mode, but disable the
| code execution on the interactive debugger, you can pass
| ``use_evalex=False`` as parameter. This will keep the debugger's
| traceback screen active, but disable code execution.
|
| It is not recommended to use this function for development with
| automatic reloading as this is badly supported. Instead you should
| be using the :command:`flask` command line script's ``run`` support.
|
| .. admonition:: Keep in Mind
|
| Flask will suppress any server error with a generic error page
| unless it is in debug mode. As such to enable just the
| interactive debugger without the code reloading, you have to
| invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
| Setting ``use_debugger`` to ``True`` without being in debug mode
| won't catch any exceptions because there won't be any to
| catch.
|
| :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
| have the server available externally as well. Defaults to
| ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
| if present.
| :param port: the port of the webserver. Defaults to ``5000`` or the
| port defined in the ``SERVER_NAME`` config variable if present.
| :param debug: if given, enable or disable debug mode. See
| :attr:`debug`.
| :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
| files to set environment variables. Will also change the working
| directory to the directory containing the first file found.
| :param options: the options to be forwarded to the underlying Werkzeug
| server. See :func:`werkzeug.serving.run_simple` for more
| information.
|
| .. versionchanged:: 1.0
| If installed, python-dotenv will be used to load environment
| variables from :file:`.env` and :file:`.flaskenv` files.
|
| The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.
|
| Threaded mode is enabled by default.
|
| .. versionchanged:: 0.10
| The default port is now picked from the ``SERVER_NAME``
| variable.
|
| send_static_file(self, filename: 'str') -> 'Response'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionadded:: 0.5
|
| test_cli_runner(self, **kwargs: 't.Any') -> 'FlaskCliRunner'
| Create a CLI runner for testing CLI commands.
| See :ref:`testing-cli`.
|
| Returns an instance of :attr:`test_cli_runner_class`, by default
| :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
| passed as the first argument.
|
| .. versionadded:: 1.0
|
| test_client(self, use_cookies: 'bool' = True, **kwargs: 't.Any') -> 'FlaskClient'
| Creates a test client for this application. For information
| about unit testing head over to :doc:`/testing`.
|
| Note that if you are testing for assertions or exceptions in your
| application code, you must set ``app.testing = True`` in order for the
| exceptions to propagate to the test client. Otherwise, the exception
| will be handled by the application (not visible to the test client) and
| the only indication of an AssertionError or other exception will be a
| 500 status code response to the test client. See the :attr:`testing`
| attribute. For example::
|
| app.testing = True
| client = app.test_client()
|
| The test client can be used in a ``with`` block to defer the closing down
| of the context until the end of the ``with`` block. This is useful if
| you want to access the context locals for testing::
|
| with app.test_client() as c:
| rv = c.get('/?vodka=42')
| assert request.args['vodka'] == '42'
|
| Additionally, you may pass optional keyword arguments that will then
| be passed to the application's :attr:`test_client_class` constructor.
| For example::
|
| from flask.testing import FlaskClient
|
| class CustomClient(FlaskClient):
| def __init__(self, *args, **kwargs):
| self._authentication = kwargs.pop("authentication")
| super(CustomClient,self).__init__( *args, **kwargs)
|
| app.test_client_class = CustomClient
| client = app.test_client(authentication='Basic ....')
|
| See :class:`~flask.testing.FlaskClient` for more information.
|
| .. versionchanged:: 0.4
| added support for ``with`` block usage for the client.
|
| .. versionadded:: 0.7
| The `use_cookies` parameter was added as well as the ability
| to override the client to be used by setting the
| :attr:`test_client_class` attribute.
|
| .. versionchanged:: 0.11
| Added `**kwargs` to support passing additional keyword arguments to
| the constructor of :attr:`test_client_class`.
|
| test_request_context(self, *args: 't.Any', **kwargs: 't.Any') -> 'RequestContext'
| Create a :class:`~flask.ctx.RequestContext` for a WSGI
| environment created from the given values. This is mostly useful
| during testing, where you may want to run a function that uses
| request data without dispatching a full request.
|
| See :doc:`/reqcontext`.
|
| Use a ``with`` block to push the context, which will make
| :data:`request` point at the request for the created
| environment. ::
|
| with app.test_request_context(...):
| generate_report()
|
| When using the shell, it may be easier to push and pop the
| context manually to avoid indentation. ::
|
| ctx = app.test_request_context(...)
| ctx.push()
| ...
| ctx.pop()
|
| Takes the same arguments as Werkzeug's
| :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
| the application. See the linked Werkzeug docs for most of the
| available arguments. Flask-specific behavior is listed here.
|
| :param path: URL path being requested.
| :param base_url: Base URL where the app is being served, which
| ``path`` is relative to. If not given, built from
| :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
| :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
| :param subdomain: Subdomain name to append to
| :data:`SERVER_NAME`.
| :param url_scheme: Scheme to use instead of
| :data:`PREFERRED_URL_SCHEME`.
| :param data: The request body, either as a string or a dict of
| form keys and values.
| :param json: If given, this is serialized as JSON and passed as
| ``data``. Also defaults ``content_type`` to
| ``application/json``.
| :param args: other positional arguments passed to
| :class:`~werkzeug.test.EnvironBuilder`.
| :param kwargs: other keyword arguments passed to
| :class:`~werkzeug.test.EnvironBuilder`.
|
| update_template_context(self, context: 'dict[str, t.Any]') -> 'None'
| Update the template context with some commonly used variables.
| This injects request, session, config and g into the template
| context as well as everything template context processors want
| to inject. Note that the as of Flask 0.6, the original values
| in the context will not be overridden if a context processor
| decides to return a value with the same key.
|
| :param context: the context as a dictionary that is updated in place
| to add extra variables.
|
| url_for(self, /, endpoint: 'str', *, _anchor: 'str | None' = None, _method: 'str | None' = None, _scheme: 'str | None' = None, _external: 'bool | None' = None, **values: 't.Any') -> 'str'
| Generate a URL to the given endpoint with the given values.
|
| This is called by :func:`flask.url_for`, and can be called
| directly as well.
|
| An *endpoint* is the name of a URL rule, usually added with
| :meth:`@app.route() <route>`, and usually the same name as the
| view function. A route defined in a :class:`~flask.Blueprint`
| will prepend the blueprint's name separated by a ``.`` to the
| endpoint.
|
| In some cases, such as email messages, you want URLs to include
| the scheme and domain, like ``https://example.com/hello``. When
| not in an active request, URLs will be external by default, but
| this requires setting :data:`SERVER_NAME` so Flask knows what
| domain to use. :data:`APPLICATION_ROOT` and
| :data:`PREFERRED_URL_SCHEME` should also be configured as
| needed. This config is only used when not in an active request.
|
| Functions can be decorated with :meth:`url_defaults` to modify
| keyword arguments before the URL is built.
|
| If building fails for some reason, such as an unknown endpoint
| or incorrect values, the app's :meth:`handle_url_build_error`
| method is called. If that returns a string, that is returned,
| otherwise a :exc:`~werkzeug.routing.BuildError` is raised.
|
| :param endpoint: The endpoint name associated with the URL to
| generate. If this starts with a ``.``, the current blueprint
| name (if any) will be used.
| :param _anchor: If given, append this as ``#anchor`` to the URL.
| :param _method: If given, generate the URL associated with this
| method for the endpoint.
| :param _scheme: If given, the URL will have this scheme if it
| is external.
| :param _external: If given, prefer the URL to be internal
| (False) or require it to be external (True). External URLs
| include the scheme and domain. When not in an active
| request, URLs are external by default.
| :param values: Values to use for the variable parts of the URL
| rule. Unknown keys are appended as query string arguments,
| like ``?a=b&c=d``.
|
| .. versionadded:: 2.2
| Moved from ``flask.url_for``, which calls this method.
|
| wsgi_app(self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 'cabc.Iterable[bytes]'
| The actual WSGI application. This is not implemented in
| :meth:`__call__` so that middlewares can be applied without
| losing a reference to the app object. Instead of doing this::
|
| app = MyMiddleware(app)
|
| It's a better idea to do this instead::
|
| app.wsgi_app = MyMiddleware(app.wsgi_app)
|
| Then you still have the original application object around and
| can continue to call methods on it.
|
| .. versionchanged:: 0.7
| Teardown events for the request and app contexts are called
| even if an unhandled error occurs. Other events may not be
| called depending on when an error occurs during dispatch.
| See :ref:`callbacks-and-errors`.
|
| :param environ: A WSGI environment.
| :param start_response: A callable accepting a status code,
| a list of headers, and an optional exception context to
| start the response.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'request_class': 'type[Request]', 'response_class':...
|
| default_config = ImmutableDict({'DEBUG': None, 'TESTING': False, ..._S...
|
| request_class = <class 'flask.wrappers.Request'>
| The request object used by default in Flask. Remembers the
| matched endpoint and view arguments.
|
| It is what ends up as :class:`~flask.request`. If you want to replace
| the request object used you can subclass this and set
| :attr:`~flask.Flask.request_class` to your subclass.
|
| The request object is a :class:`~werkzeug.wrappers.Request` subclass and
| provides all of the attributes Werkzeug defines plus a few Flask
| specific ones.
|
|
| response_class = <class 'flask.wrappers.Response'>
| The response object that is used by default in Flask. Works like the
| response object from Werkzeug but is set to have an HTML mimetype by
| default. Quite often you don't have to create this object yourself because
| :meth:`~flask.Flask.make_response` will take care of that for you.
|
| If you want to replace the response object used you can subclass this and
| set :attr:`~flask.Flask.response_class` to your subclass.
|
| .. versionchanged:: 1.0
| JSON support is added to the response, like the request. This is useful
| when testing to get the test client response data as JSON.
|
| .. versionchanged:: 1.0
|
| Added :attr:`max_cookie_size`.
|
|
| session_interface = <flask.sessions.SecureCookieSessionInterface objec...
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.app.App:
|
| add_template_filter(self, f: 'ft.TemplateFilterCallable', name: 'str | None' = None) -> 'None'
| Register a custom template filter. Works exactly like the
| :meth:`template_filter` decorator.
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| add_template_global(self, f: 'ft.TemplateGlobalCallable', name: 'str | None' = None) -> 'None'
| Register a custom template global function. Works exactly like the
| :meth:`template_global` decorator.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global function, otherwise the
| function name will be used.
|
| add_template_test(self, f: 'ft.TemplateTestCallable', name: 'str | None' = None) -> 'None'
| Register a custom template test. Works exactly like the
| :meth:`template_test` decorator.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| add_url_rule(self, rule: 'str', endpoint: 'str | None' = None, view_func: 'ft.RouteCallable | None' = None, provide_automatic_options: 'bool | None' = None, **options: 't.Any') -> 'None'
| 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.
|
| auto_find_instance_path(self) -> 'str'
| Tries to locate the instance path if it was not provided to the
| constructor of the application class. It will basically calculate
| the path to a folder named ``instance`` next to your main file or
| the package.
|
| .. versionadded:: 0.8
|
| create_global_jinja_loader(self) -> 'DispatchingJinjaLoader'
| Creates the loader for the Jinja environment. Can be used to
| override just the loader and keeping the rest unchanged. It's
| discouraged to override this function. Instead one should override
| the :meth:`jinja_loader` function instead.
|
| The global loader dispatches between the loaders of the application
| and the individual blueprints.
|
| .. versionadded:: 0.7
|
| handle_url_build_error(self, error: 'BuildError', endpoint: 'str', values: 'dict[str, t.Any]') -> 'str'
| Called by :meth:`.url_for` if a
| :exc:`~werkzeug.routing.BuildError` was raised. If this returns
| a value, it will be returned by ``url_for``, otherwise the error
| will be re-raised.
|
| Each function in :attr:`url_build_error_handlers` is called with
| ``error``, ``endpoint`` and ``values``. If a function returns
| ``None`` or raises a ``BuildError``, it is skipped. Otherwise,
| its return value is returned by ``url_for``.
|
| :param error: The active ``BuildError`` being handled.
| :param endpoint: The endpoint being built.
| :param values: The keyword arguments passed to ``url_for``.
|
| inject_url_defaults(self, endpoint: 'str', values: 'dict[str, t.Any]') -> 'None'
| Injects the URL defaults for the given endpoint directly into
| the values dictionary passed. This is used internally and
| automatically called on URL building.
|
| .. versionadded:: 0.7
|
| iter_blueprints(self) -> 't.ValuesView[Blueprint]'
| Iterates over all blueprints by the order they were registered.
|
| .. versionadded:: 0.11
|
| make_aborter(self) -> 'Aborter'
| Create the object to assign to :attr:`aborter`. That object
| is called by :func:`flask.abort` to raise HTTP errors, and can
| be called directly as well.
|
| By default, this creates an instance of :attr:`aborter_class`,
| which defaults to :class:`werkzeug.exceptions.Aborter`.
|
| .. versionadded:: 2.2
|
| make_config(self, instance_relative: 'bool' = False) -> 'Config'
| Used to create the config attribute by the Flask constructor.
| The `instance_relative` parameter is passed in from the constructor
| of Flask (there named `instance_relative_config`) and indicates if
| the config should be relative to the instance path or the root path
| of the application.
|
| .. versionadded:: 0.8
|
| redirect(self, location: 'str', code: 'int' = 302) -> 'BaseResponse'
| Create a redirect response object.
|
| This is called by :func:`flask.redirect`, and can be called
| directly as well.
|
| :param location: The URL to redirect to.
| :param code: The status code for the redirect.
|
| .. versionadded:: 2.2
| Moved from ``flask.redirect``, which calls this method.
|
| register_blueprint(self, blueprint: 'Blueprint', **options: 't.Any') -> 'None'
| Register a :class:`~flask.Blueprint` on the application. Keyword
| arguments passed to this method will override the defaults set on the
| blueprint.
|
| Calls the blueprint's :meth:`~flask.Blueprint.register` method after
| recording the blueprint in the application's :attr:`blueprints`.
|
| :param blueprint: The blueprint to register.
| :param url_prefix: Blueprint routes will be prefixed with this.
| :param subdomain: Blueprint routes will match on this subdomain.
| :param url_defaults: Blueprint routes will use these default values for
| view arguments.
| :param options: Additional keyword arguments are passed to
| :class:`~flask.blueprints.BlueprintSetupState`. They can be
| accessed in :meth:`~flask.Blueprint.record` callbacks.
|
| .. versionchanged:: 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``.
|
| .. versionadded:: 0.7
|
| select_jinja_autoescape(self, filename: 'str | None') -> 'bool'
| Returns ``True`` if autoescaping should be active for the given
| template name. If no template name is given, returns `True`.
|
| .. versionchanged:: 2.2
| Autoescaping is now enabled by default for ``.svg`` files.
|
| .. versionadded:: 0.5
|
| shell_context_processor(self, f: 'T_shell_context_processor') -> 'T_shell_context_processor'
| Registers a shell context processor function.
|
| .. versionadded:: 0.11
|
| should_ignore_error(self, error: 'BaseException | None') -> 'bool'
| This is called to figure out if an error should be ignored
| or not as far as the teardown system is concerned. If this
| function returns ``True`` then the teardown handlers will not be
| passed the error.
|
| .. versionadded:: 0.10
|
| teardown_appcontext(self, f: 'T_teardown') -> 'T_teardown'
| Registers a function to be called when the application
| context is popped. The application context is typically popped
| after the request context for each request, at the end of CLI
| commands, or after a manually pushed context ends.
|
| .. code-block:: python
|
| with app.app_context():
| ...
|
| When the ``with`` block exits (or ``ctx.pop()`` is called), the
| teardown functions are called just before the app context is
| made inactive. Since a request context typically also manages an
| application context it would also be called when you pop a
| request context.
|
| 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.
|
| .. versionadded:: 0.9
|
| template_filter(self, name: 'str | None' = None) -> 't.Callable[[T_template_filter], T_template_filter]'
| A decorator that is used to register custom template filter.
| You can specify a name for the filter, otherwise the function
| name will be used. Example::
|
| @app.template_filter()
| def reverse(s):
| return s[::-1]
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| template_global(self, name: 'str | None' = None) -> 't.Callable[[T_template_global], T_template_global]'
| A decorator that is used to register a custom template global function.
| You can specify a name for the global function, otherwise the function
| name will be used. Example::
|
| @app.template_global()
| def double(n):
| return 2 * n
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global function, otherwise the
| function name will be used.
|
| template_test(self, name: 'str | None' = None) -> 't.Callable[[T_template_test], T_template_test]'
| A decorator that is used to register custom template test.
| You can specify a name for the test, otherwise the function
| name will be used. Example::
|
| @app.template_test()
| def is_prime(n):
| if n == 2:
| return True
| for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
| if n % i == 0:
| return False
| return True
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| trap_http_exception(self, e: 'Exception') -> 'bool'
| Checks if an HTTP exception should be trapped or not. By default
| this will return ``False`` for all exceptions except for a bad request
| key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
| also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
|
| This is called for all HTTP exceptions raised by a view function.
| If it returns ``True`` for any exception the error handler for this
| exception is not called and it shows up as regular exception in the
| traceback. This is helpful for debugging implicitly raised HTTP
| exceptions.
|
| .. versionchanged:: 1.0
| Bad request errors are not trapped by default in debug mode.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Readonly properties inherited from flask.sansio.app.App:
|
| jinja_env
| The Jinja environment used to load templates.
|
| The environment is created the first time this property is
| accessed. Changing :attr:`jinja_options` after that will have no
| effect.
|
| logger
| A standard Python :class:`~logging.Logger` for the app, with
| the same name as :attr:`name`.
|
| In debug mode, the logger's :attr:`~logging.Logger.level` will
| be set to :data:`~logging.DEBUG`.
|
| If there are no handlers configured, a default handler will be
| added. See :doc:`/logging` for more information.
|
| .. versionchanged:: 1.1.0
| The logger takes the same name as :attr:`name` rather than
| hard-coding ``"flask.app"``.
|
| .. versionchanged:: 1.0.0
| Behavior was simplified. The logger is always named
| ``"flask.app"``. The level is only set during configuration,
| it doesn't check ``app.debug`` each time. Only one format is
| used, not different ones depending on ``app.debug``. No
| handlers are removed, and a handler is only added if no
| handlers are already configured.
|
| .. versionadded:: 0.3
|
| name
| The name of the application. This is usually the import name
| with the difference that it's guessed from the run file if the
| import name is main. This name is used as a display name when
| Flask needs the name of the application. It can be set and overridden
| to change the value.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Data descriptors inherited from flask.sansio.app.App:
|
| debug
| Whether debug mode is enabled. When using ``flask run`` to start the
| development server, an interactive debugger will be shown for unhandled
| exceptions, and the server will be reloaded when code changes. This maps to the
| :data:`DEBUG` config key. It may not behave as expected if set late.
|
| **Do not enable debug mode when deploying in production.**
|
| Default: ``False``
|
| permanent_session_lifetime
|
| secret_key
|
| testing
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from flask.sansio.app.App:
|
| aborter_class = <class 'werkzeug.exceptions.Aborter'>
| When passed a dict of code -> exception items it can be used as
| callable that raises exceptions. If the first argument to the
| callable is an integer it will be looked up in the mapping, if it's
| a WSGI application it will be raised in a proxy exception.
|
| The rest of the arguments are forwarded to the exception constructor.
|
|
| app_ctx_globals_class = <class 'flask.ctx._AppCtxGlobals'>
| A plain object. Used as a namespace for storing data during an
| application context.
|
| Creating an app context automatically creates this object, which is
| made available as the :data:`g` proxy.
|
| .. describe:: 'key' in g
|
| Check whether an attribute is present.
|
| .. versionadded:: 0.10
|
| .. describe:: iter(g)
|
| Return an iterator over the attribute names.
|
| .. versionadded:: 0.10
|
|
| config_class = <class 'flask.config.Config'>
| Works exactly like a dict but provides ways to fill it from files
| or special dictionaries. There are two common patterns to populate the
| config.
|
| Either you can fill the config from a config file::
|
| app.config.from_pyfile('yourconfig.cfg')
|
| Or alternatively you can define the configuration options in the
| module that calls :meth:`from_object` or provide an import path to
| a module that should be loaded. It is also possible to tell it to
| use the same module and with that provide the configuration values
| just before the call::
|
| DEBUG = True
| SECRET_KEY = 'development key'
| app.config.from_object(__name__)
|
| In both cases (loading from any Python file or loading from modules),
| only uppercase keys are added to the config. This makes it possible to use
| lowercase values in the config file for temporary values that are not added
| to the config or to define the config keys in the same file that implements
| the application.
|
| Probably the most interesting way to load configurations is from an
| environment variable pointing to a file::
|
| app.config.from_envvar('YOURAPPLICATION_SETTINGS')
|
| In this case before launching the application you have to set this
| environment variable to the file you want to use. On Linux and OS X
| use the export statement::
|
| export YOURAPPLICATION_SETTINGS='/path/to/config/file'
|
| On windows use `set` instead.
|
| :param root_path: path to which files are read relative from. When the
| config object is created by the application, this is
| the application's :attr:`~flask.Flask.root_path`.
| :param defaults: an optional dictionary of default values
|
|
| jinja_environment = <class 'flask.templating.Environment'>
| Works like a regular Jinja environment but has some additional
| knowledge of how Flask's blueprint works so that it can prepend the
| name of the blueprint to referenced templates if necessary.
|
|
| jinja_options = {}
|
| json_provider_class = <class 'flask.json.provider.DefaultJSONProvider'...
| Provide JSON operations using Python's built-in :mod:`json`
| library. Serializes the following additional data types:
|
| - :class:`datetime.datetime` and :class:`datetime.date` are
| serialized to :rfc:`822` strings. This is the same as the HTTP
| date format.
| - :class:`uuid.UUID` is serialized to a string.
| - :class:`dataclasses.dataclass` is passed to
| :func:`dataclasses.asdict`.
| - :class:`~markupsafe.Markup` (or any object with a ``__html__``
| method) will call the ``__html__`` method to get a string.
|
|
| test_cli_runner_class = None
|
| test_client_class = None
|
| url_map_class = <class 'werkzeug.routing.map.Map'>
| The map class stores all the URL rules and some configuration
| parameters. Some of the configuration values are only stored on the
| `Map` instance since those affect all rules, others are just defaults
| and can be overridden for each rule. Note that you have to specify all
| arguments besides the `rules` as keyword arguments!
|
| :param rules: sequence of url rules for this map.
| :param default_subdomain: The default subdomain for rules without a
| subdomain defined.
| :param strict_slashes: If a rule ends with a slash but the matched
| URL does not, redirect to the URL with a trailing slash.
| :param merge_slashes: Merge consecutive slashes when matching or
| building URLs. Matches will redirect to the normalized URL.
| Slashes in variable parts are not merged.
| :param redirect_defaults: This will redirect to the default rule if it
| wasn't visited that way. This helps creating
| unique URLs.
| :param converters: A dict of converters that adds additional converters
| to the list of converters. If you redefine one
| converter this will override the original one.
| :param sort_parameters: If set to `True` the url parameters are sorted.
| See `url_encode` for more details.
| :param sort_key: The sort key function for `url_encode`.
| :param host_matching: if set to `True` it enables the host matching
| feature and disables the subdomain one. If
| enabled the `host` parameter to rules is used
| instead of the `subdomain` one.
|
| .. versionchanged:: 3.0
| The ``charset`` and ``encoding_errors`` parameters were removed.
|
| .. versionchanged:: 1.0
| If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules will match.
|
| .. versionchanged:: 1.0
| The ``merge_slashes`` parameter was added.
|
| .. versionchanged:: 0.7
| The ``encoding_errors`` and ``host_matching`` parameters were added.
|
| .. versionchanged:: 0.5
| The ``sort_parameters`` and ``sort_key`` parameters were added.
|
|
| url_rule_class = <class 'werkzeug.routing.rules.Rule'>
| A Rule represents one URL pattern. There are some options for `Rule`
| that change the way it behaves and are passed to the `Rule` constructor.
| Note that besides the rule-string all arguments *must* be keyword arguments
| in order to not break the application on Werkzeug upgrades.
|
| `string`
| Rule strings basically are just normal URL paths with placeholders in
| the format ``<converter(arguments):name>`` where the converter and the
| arguments are optional. If no converter is defined the `default`
| converter is used which means `string` in the normal configuration.
|
| URL rules that end with a slash are branch URLs, others are leaves.
| If you have `strict_slashes` enabled (which is the default), all
| branch URLs that are matched without a trailing slash will trigger a
| redirect to the same URL with the missing slash appended.
|
| The converters are defined on the `Map`.
|
| `endpoint`
| The endpoint for this rule. This can be anything. A reference to a
| function, a string, a number etc. The preferred way is using a string
| because the endpoint is used for URL generation.
|
| `defaults`
| An optional dict with defaults for other rules with the same endpoint.
| This is a bit tricky but useful if you want to have unique URLs::
|
| url_map = Map([
| Rule('/all/', defaults={'page': 1}, endpoint='all_entries'),
| Rule('/all/page/<int:page>', endpoint='all_entries')
| ])
|
| If a user now visits ``http://example.com/all/page/1`` they will be
| redirected to ``http://example.com/all/``. If `redirect_defaults` is
| disabled on the `Map` instance this will only affect the URL
| generation.
|
| `subdomain`
| The subdomain rule string for this rule. If not specified the rule
| only matches for the `default_subdomain` of the map. If the map is
| not bound to a subdomain this feature is disabled.
|
| Can be useful if you want to have user profiles on different subdomains
| and all subdomains are forwarded to your application::
|
| url_map = Map([
| Rule('/', subdomain='<username>', endpoint='user/homepage'),
| Rule('/stats', subdomain='<username>', endpoint='user/stats')
| ])
|
| `methods`
| A sequence of http methods this rule applies to. If not specified, all
| methods are allowed. For example this can be useful if you want different
| endpoints for `POST` and `GET`. If methods are defined and the path
| matches but the method matched against is not in this list or in the
| list of another rule for that path the error raised is of the type
| `MethodNotAllowed` rather than `NotFound`. If `GET` is present in the
| list of methods and `HEAD` is not, `HEAD` is added automatically.
|
| `strict_slashes`
| Override the `Map` setting for `strict_slashes` only for this rule. If
| not specified the `Map` setting is used.
|
| `merge_slashes`
| Override :attr:`Map.merge_slashes` for this rule.
|
| `build_only`
| Set this to True and the rule will never match but will create a URL
| that can be build. This is useful if you have resources on a subdomain
| or folder that are not handled by the WSGI application (like static data)
|
| `redirect_to`
| If given this must be either a string or callable. In case of a
| callable it's called with the url adapter that triggered the match and
| the values of the URL as keyword arguments and has to return the target
| for the redirect, otherwise it has to be a string with placeholders in
| rule syntax::
|
| def foo_with_slug(adapter, id):
| # ask the database for the slug for the old id. this of
| # course has nothing to do with werkzeug.
| return f'foo/{Foo.get_slug_for_id(id)}'
|
| url_map = Map([
| Rule('/foo/<slug>', endpoint='foo'),
| Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'),
| Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug)
| ])
|
| When the rule is matched the routing system will raise a
| `RequestRedirect` exception with the target for the redirect.
|
| Keep in mind that the URL will be joined against the URL root of the
| script so don't use a leading slash on the target URL unless you
| really mean root of that domain.
|
| `alias`
| If enabled this rule serves as an alias for another rule with the same
| endpoint and arguments.
|
| `host`
| If provided and the URL map has host matching enabled this can be
| used to provide a match rule for the whole host. This also means
| that the subdomain feature is disabled.
|
| `websocket`
| If ``True``, this rule is only matches for WebSocket (``ws://``,
| ``wss://``) requests. By default, rules will only match for HTTP
| requests.
|
| .. versionchanged:: 2.1
| Percent-encoded newlines (``%0a``), which are decoded by WSGI
| servers, are considered when routing instead of terminating the
| match early.
|
| .. versionadded:: 1.0
| Added ``websocket``.
|
| .. versionadded:: 1.0
| Added ``merge_slashes``.
|
| .. versionadded:: 0.7
| Added ``alias`` and ``host``.
|
| .. versionchanged:: 0.6.1
| ``HEAD`` is added to ``methods`` if ``GET`` is present.
|
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.scaffold.Scaffold:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| after_request(self, 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 :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`.
|
| before_request(self, 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.
|
| .. 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`.
|
| context_processor(self, 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 :meth:`.Blueprint.app_context_processor`.
|
| delete(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["DELETE"]``.
|
| .. versionadded:: 2.0
|
| endpoint(self, endpoint: 'str') -> 't.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
| :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.
|
| errorhandler(self, code_or_exception: 'type[Exception] | int') -> 't.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 :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
|
| get(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["GET"]``.
|
| .. versionadded:: 2.0
|
| patch(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PATCH"]``.
|
| .. versionadded:: 2.0
|
| post(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["POST"]``.
|
| .. versionadded:: 2.0
|
| put(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PUT"]``.
|
| .. versionadded:: 2.0
|
| register_error_handler(self, code_or_exception: 'type[Exception] | int', f: 'ft.ErrorHandlerCallable') -> 'None'
| Alternative error attach function to the :meth:`errorhandler`
| decorator that is more straightforward to use for non decorator
| usage.
|
| .. versionadded:: 0.7
|
| route(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_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.
|
| .. 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.
|
| teardown_request(self, 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.
|
| .. 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`.
|
| url_defaults(self, 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 :meth:`.Blueprint.app_url_defaults`.
|
| url_value_preprocessor(self, 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
| :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`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from flask.sansio.scaffold.Scaffold:
|
| has_static_folder
| ``True`` if :attr:`static_folder` is set.
|
| .. versionadded:: 0.5
|
| 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.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data descriptors inherited from flask.sansio.scaffold.Scaffold:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| static_folder
| The absolute path to the configured static folder. ``None``
| if no static folder is set.
|
| static_url_path
| 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`.
DATA
T_shell_context_processor = ~T_shell_context_processor
T_teardown = ~T_teardown
T_template_filter = ~T_template_filter
T_template_global = ~T_template_global
T_template_test = ~T_template_test
appcontext_tearing_down = <blinker.base.NamedSignal object at 0x000002...
current_app = <LocalProxy unbound>
g = <LocalProxy unbound>
got_request_exception = <blinker.base.NamedSignal object at 0x00000232...
request = <LocalProxy unbound>
request_ctx = <LocalProxy unbound>
request_finished = <blinker.base.NamedSignal object at 0x0000023208467...
request_started = <blinker.base.NamedSignal object at 0x00000232084673...
request_tearing_down = <blinker.base.NamedSignal object at 0x000002320...
session = <LocalProxy unbound>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\app.py
flask.appcontext_popped
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.appcontext_pushed
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.appcontext_tearing_down
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.before_render_template
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.blueprints
Python Library Documentation: module flask.blueprints in flask
NAME
flask.blueprints
CLASSES
flask.sansio.blueprints.Blueprint(flask.sansio.scaffold.Scaffold)
Blueprint
class Blueprint(flask.sansio.blueprints.Blueprint)
| Blueprint(name: 'str', import_name: 'str', static_folder: 'str | os.PathLike[str] | None' = None, static_url_path: 'str | None' = None, template_folder: 'str | os.PathLike[str] | None' = None, url_prefix: 'str | None' = None, subdomain: 'str | None' = None, url_defaults: 'dict[str, t.Any] | None' = None, root_path: 'str | None' = None, cli_group: 'str | None' = <object object at 0x00000232059594F0>) -> 'None'
|
| Method resolution order:
| Blueprint
| flask.sansio.blueprints.Blueprint
| flask.sansio.scaffold.Scaffold
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', import_name: 'str', static_folder: 'str | os.PathLike[str] | None' = None, static_url_path: 'str | None' = None, template_folder: 'str | os.PathLike[str] | None' = None, url_prefix: 'str | None' = None, subdomain: 'str | None' = None, url_defaults: 'dict[str, t.Any] | None' = None, root_path: 'str | None' = None, cli_group: 'str | None' = <object object at 0x00000232059594F0>) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| get_send_file_max_age(self, filename: 'str | None') -> 'int | None'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionchanged:: 2.0
| The default configuration is ``None`` instead of 12 hours.
|
| .. versionadded:: 0.9
|
| open_resource(self, resource: 'str', mode: 'str' = 'rb', encoding: 'str | None' = 'utf-8') -> 't.IO[t.AnyStr]'
| Open a resource file relative to :attr:`root_path` for reading. The
| blueprint-relative equivalent of the app's :meth:`~.Flask.open_resource`
| method.
|
| :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"``.
| :param encoding: Open the file with this encoding when opening in text
| mode. This is ignored when opening in binary mode.
|
| .. versionchanged:: 3.1
| Added the ``encoding`` parameter.
|
| send_static_file(self, filename: 'str') -> 'Response'
| 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.
|
| Note this is a duplicate of the same method in the Flask
| class.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.blueprints.Blueprint:
|
| add_app_template_filter(self, f: 'ft.TemplateFilterCallable', name: 'str | None' = None) -> 'None'
| Register a template filter, available in any template rendered by the
| application. Works like the :meth:`app_template_filter` decorator. Equivalent to
| :meth:`.Flask.add_template_filter`.
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| add_app_template_global(self, f: 'ft.TemplateGlobalCallable', name: 'str | None' = None) -> 'None'
| Register a template global, available in any template rendered by the
| application. Works like the :meth:`app_template_global` decorator. Equivalent to
| :meth:`.Flask.add_template_global`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global, otherwise the
| function name will be used.
|
| add_app_template_test(self, f: 'ft.TemplateTestCallable', name: 'str | None' = None) -> 'None'
| Register a template test, available in any template rendered by the
| application. Works like the :meth:`app_template_test` decorator. Equivalent to
| :meth:`.Flask.add_template_test`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| add_url_rule(self, rule: 'str', endpoint: 'str | None' = None, view_func: 'ft.RouteCallable | None' = None, provide_automatic_options: 'bool | None' = None, **options: 't.Any') -> 'None'
| Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for
| full documentation.
|
| The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,
| used with :func:`url_for`, is prefixed with the blueprint's name.
|
| after_app_request(self, f: 'T_after_request') -> 'T_after_request'
| Like :meth:`after_request`, but after every request, not only those handled
| by the blueprint. Equivalent to :meth:`.Flask.after_request`.
|
| app_context_processor(self, f: 'T_template_context_processor') -> 'T_template_context_processor'
| Like :meth:`context_processor`, but for templates rendered by every view, not
| only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.
|
| app_errorhandler(self, code: 'type[Exception] | int') -> 't.Callable[[T_error_handler], T_error_handler]'
| Like :meth:`errorhandler`, but for every request, not only those handled by
| the blueprint. Equivalent to :meth:`.Flask.errorhandler`.
|
| app_template_filter(self, name: 'str | None' = None) -> 't.Callable[[T_template_filter], T_template_filter]'
| Register a template filter, available in any template rendered by the
| application. Equivalent to :meth:`.Flask.template_filter`.
|
| :param name: the optional name of the filter, otherwise the
| function name will be used.
|
| app_template_global(self, name: 'str | None' = None) -> 't.Callable[[T_template_global], T_template_global]'
| Register a template global, available in any template rendered by the
| application. Equivalent to :meth:`.Flask.template_global`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the global, otherwise the
| function name will be used.
|
| app_template_test(self, name: 'str | None' = None) -> 't.Callable[[T_template_test], T_template_test]'
| Register a template test, available in any template rendered by the
| application. Equivalent to :meth:`.Flask.template_test`.
|
| .. versionadded:: 0.10
|
| :param name: the optional name of the test, otherwise the
| function name will be used.
|
| app_url_defaults(self, f: 'T_url_defaults') -> 'T_url_defaults'
| Like :meth:`url_defaults`, but for every request, not only those handled by
| the blueprint. Equivalent to :meth:`.Flask.url_defaults`.
|
| app_url_value_preprocessor(self, f: 'T_url_value_preprocessor') -> 'T_url_value_preprocessor'
| Like :meth:`url_value_preprocessor`, but for every request, not only those
| handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.
|
| before_app_request(self, f: 'T_before_request') -> 'T_before_request'
| Like :meth:`before_request`, but before every request, not only those handled
| by the blueprint. Equivalent to :meth:`.Flask.before_request`.
|
| make_setup_state(self, app: 'App', options: 'dict[str, t.Any]', first_registration: 'bool' = False) -> 'BlueprintSetupState'
| Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
| object that is later passed to the register callback functions.
| Subclasses can override this to return a subclass of the setup state.
|
| record(self, func: 'DeferredSetupFunction') -> '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 :meth:`make_setup_state`
| method.
|
| record_once(self, func: 'DeferredSetupFunction') -> 'None'
| Works like :meth:`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(self, app: 'App', options: 'dict[str, t.Any]') -> 'None'
| Called by :meth:`Flask.register_blueprint` to register all
| views and callbacks registered on the blueprint with the
| application. Creates a :class:`.BlueprintSetupState` and calls
| each :meth:`record` callback with it.
|
| :param app: The application this blueprint is being registered
| with.
| :param options: Keyword arguments forwarded from
| :meth:`~Flask.register_blueprint`.
|
| .. versionchanged:: 2.3
| Nested blueprints now correctly apply subdomains.
|
| .. versionchanged:: 2.1
| Registering the same blueprint with the same name multiple
| times is an error.
|
| .. versionchanged:: 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.
|
| .. versionchanged:: 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(self, blueprint: 'Blueprint', **options: 't.Any') -> 'None'
| Register a :class:`~flask.Blueprint` on this blueprint. Keyword
| arguments passed to this method will override the defaults set
| on the blueprint.
|
| .. versionchanged:: 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``.
|
| .. versionadded:: 2.0
|
| teardown_app_request(self, f: 'T_teardown') -> 'T_teardown'
| Like :meth:`teardown_request`, but after every request, not only those
| handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.
|
| ----------------------------------------------------------------------
| Methods inherited from flask.sansio.scaffold.Scaffold:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| after_request(self, 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 :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`.
|
| before_request(self, 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.
|
| .. 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`.
|
| context_processor(self, 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 :meth:`.Blueprint.app_context_processor`.
|
| delete(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["DELETE"]``.
|
| .. versionadded:: 2.0
|
| endpoint(self, endpoint: 'str') -> 't.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
| :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.
|
| errorhandler(self, code_or_exception: 'type[Exception] | int') -> 't.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 :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
|
| get(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["GET"]``.
|
| .. versionadded:: 2.0
|
| patch(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PATCH"]``.
|
| .. versionadded:: 2.0
|
| post(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["POST"]``.
|
| .. versionadded:: 2.0
|
| put(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_route]'
| Shortcut for :meth:`route` with ``methods=["PUT"]``.
|
| .. versionadded:: 2.0
|
| register_error_handler(self, code_or_exception: 'type[Exception] | int', f: 'ft.ErrorHandlerCallable') -> 'None'
| Alternative error attach function to the :meth:`errorhandler`
| decorator that is more straightforward to use for non decorator
| usage.
|
| .. versionadded:: 0.7
|
| route(self, rule: 'str', **options: 't.Any') -> 't.Callable[[T_route], T_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.
|
| .. 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.
|
| teardown_request(self, 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.
|
| .. 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`.
|
| url_defaults(self, 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 :meth:`.Blueprint.app_url_defaults`.
|
| url_value_preprocessor(self, 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
| :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`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from flask.sansio.scaffold.Scaffold:
|
| has_static_folder
| ``True`` if :attr:`static_folder` is set.
|
| .. versionadded:: 0.5
|
| 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.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data descriptors inherited from flask.sansio.scaffold.Scaffold:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| static_folder
| The absolute path to the configured static folder. ``None``
| if no static folder is set.
|
| static_url_path
| 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`.
DATA
current_app = <LocalProxy unbound>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\blueprints.py
flask.cli
Python Library Documentation: module flask.cli in flask
NAME
flask.cli
CLASSES
builtins.object
ScriptInfo
click.core.Group(click.core.Command)
AppGroup
FlaskGroup
click.exceptions.UsageError(click.exceptions.ClickException)
NoAppException
click.types.ParamType(typing.Generic, abc.ABC)
CertParamType
click.types.Path(click.types.ParamType)
SeparatedPathType
class AppGroup(click.core.Group)
| AppGroup(name: 'str | None' = None, commands: 'cabc.MutableMapping[str, Command] | cabc.Sequence[Command] | None' = None, invoke_without_command: 'bool' = False, no_args_is_help: 'bool | None' = None, subcommand_metavar: 'str | None' = None, chain: 'bool' = False, result_callback: 't.Callable[..., t.Any] | None' = None, **kwargs: 't.Any') -> 'None'
|
| This works similar to a regular click :class:`~click.Group` but it
| changes the behavior of the :meth:`command` decorator so that it
| automatically wraps the functions in :func:`with_appcontext`.
|
| Not to be confused with :class:`FlaskGroup`.
|
| Method resolution order:
| AppGroup
| click.core.Group
| click.core.Command
| builtins.object
|
| Methods defined here:
|
| command(self, *args: 't.Any', **kwargs: 't.Any') -> 't.Callable[[t.Callable[..., t.Any]], click.Command]'
| This works exactly like the method of the same name on a regular
| :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
| unless it's disabled by passing ``with_appcontext=False``.
|
| group(self, *args: 't.Any', **kwargs: 't.Any') -> 't.Callable[[t.Callable[..., t.Any]], click.Group]'
| This works exactly like the method of the same name on a regular
| :class:`click.Group` but it defaults the group class to
| :class:`AppGroup`.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from click.core.Group:
|
| __init__(self, name: 'str | None' = None, commands: 'cabc.MutableMapping[str, Command] | cabc.Sequence[Command] | None' = None, invoke_without_command: 'bool' = False, no_args_is_help: 'bool | None' = None, subcommand_metavar: 'str | None' = None, chain: 'bool' = False, result_callback: 't.Callable[..., t.Any] | None' = None, **kwargs: 't.Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| add_command(self, cmd: 'Command', name: 'str | None' = None) -> 'None'
| Registers another :class:`Command` with this group. If the name
| is not provided, the name of the command is used.
|
| collect_usage_pieces(self, ctx: 'Context') -> 'list[str]'
| Returns all the pieces that go into the usage line and returns
| it as a list of strings.
|
| format_commands(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Extra format methods for multi methods that adds all the commands
| after the options.
|
| format_options(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes all the options into the formatter if they exist.
|
| get_command(self, ctx: 'Context', cmd_name: 'str') -> 'Command | None'
| Given a context and a command name, this returns a :class:`Command`
| object if it exists or returns ``None``.
|
| invoke(self, ctx: 'Context') -> 't.Any'
| Given a context, this invokes the attached callback (if it exists)
| in the right way.
|
| list_commands(self, ctx: 'Context') -> 'list[str]'
| Returns a list of subcommand names in the order they should appear.
|
| parse_args(self, ctx: 'Context', args: 'list[str]') -> 'list[str]'
|
| resolve_command(self, ctx: 'Context', args: 'list[str]') -> 'tuple[str | None, Command | None, list[str]]'
|
| result_callback(self, replace: 'bool' = False) -> 't.Callable[[F], F]'
| Adds a result callback to the command. By default if a
| result callback is already registered this will chain them but
| this can be disabled with the `replace` parameter. The result
| callback is invoked with the return value of the subcommand
| (or the list of return values from all subcommands if chaining
| is enabled) as well as the parameters as they would be passed
| to the main callback.
|
| Example::
|
| @click.group()
| @click.option('-i', '--input', default=23)
| def cli(input):
| return 42
|
| @cli.result_callback()
| def process_result(result, input):
| return result + input
|
| :param replace: if set to `True` an already existing result
| callback will be removed.
|
| .. versionchanged:: 8.0
| Renamed from ``resultcallback``.
|
| .. versionadded:: 3.0
|
| shell_complete(self, ctx: 'Context', incomplete: 'str') -> 'list[CompletionItem]'
| Return a list of completions for the incomplete value. Looks
| at the names of options, subcommands, and chained
| multi-commands.
|
| :param ctx: Invocation context for this command.
| :param incomplete: Value being completed. May be empty.
|
| .. versionadded:: 8.0
|
| to_info_dict(self, ctx: 'Context') -> 'dict[str, t.Any]'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.core.Group:
|
| allow_extra_args = True
|
| allow_interspersed_args = False
|
| command_class = None
|
| group_class = None
|
| ----------------------------------------------------------------------
| Methods inherited from click.core.Command:
|
| __call__(self, *args: 't.Any', **kwargs: 't.Any') -> 't.Any'
| Alias for :meth:`main`.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| format_epilog(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the epilog into the formatter if it exists.
|
| format_help(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the help into the formatter if it exists.
|
| This is a low-level method called by :meth:`get_help`.
|
| This calls the following methods:
|
| - :meth:`format_usage`
| - :meth:`format_help_text`
| - :meth:`format_options`
| - :meth:`format_epilog`
|
| format_help_text(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the help text to the formatter if it exists.
|
| format_usage(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the usage line into the formatter.
|
| This is a low-level method called by :meth:`get_usage`.
|
| get_help(self, ctx: 'Context') -> 'str'
| Formats the help into a string and returns it.
|
| Calls :meth:`format_help` internally.
|
| get_help_option(self, ctx: 'Context') -> 'Option | None'
| Returns the help option object.
|
| Skipped if :attr:`add_help_option` is ``False``.
|
| .. versionchanged:: 8.1.8
| The help option is now cached to avoid creating it multiple times.
|
| get_help_option_names(self, ctx: 'Context') -> 'list[str]'
| Returns the names for the help option.
|
| get_params(self, ctx: 'Context') -> 'list[Parameter]'
|
| get_short_help_str(self, limit: 'int' = 45) -> 'str'
| Gets short help for the command or makes it by shortening the
| long help string.
|
| get_usage(self, ctx: 'Context') -> 'str'
| Formats the usage line into a string and returns it.
|
| Calls :meth:`format_usage` internally.
|
| main(self, args: 'cabc.Sequence[str] | None' = None, prog_name: 'str | None' = None, complete_var: 'str | None' = None, standalone_mode: 'bool' = True, windows_expand_args: 'bool' = True, **extra: 't.Any') -> 't.Any'
| This is the way to invoke a script with all the bells and
| whistles as a command line application. This will always terminate
| the application after a call. If this is not wanted, ``SystemExit``
| needs to be caught.
|
| This method is also available by directly calling the instance of
| a :class:`Command`.
|
| :param args: the arguments that should be used for parsing. If not
| provided, ``sys.argv[1:]`` is used.
| :param prog_name: the program name that should be used. By default
| the program name is constructed by taking the file
| name from ``sys.argv[0]``.
| :param complete_var: the environment variable that controls the
| bash completion support. The default is
| ``"_<prog_name>_COMPLETE"`` with prog_name in
| uppercase.
| :param standalone_mode: the default behavior is to invoke the script
| in standalone mode. Click will then
| handle exceptions and convert them into
| error messages and the function will never
| return but shut down the interpreter. If
| this is set to `False` they will be
| propagated to the caller and the return
| value of this function is the return value
| of :meth:`invoke`.
| :param windows_expand_args: Expand glob patterns, user dir, and
| env vars in command line args on Windows.
| :param extra: extra keyword arguments are forwarded to the context
| constructor. See :class:`Context` for more information.
|
| .. versionchanged:: 8.0.1
| Added the ``windows_expand_args`` parameter to allow
| disabling command line arg expansion on Windows.
|
| .. versionchanged:: 8.0
| When taking arguments from ``sys.argv`` on Windows, glob
| patterns, user dir, and env vars are expanded.
|
| .. versionchanged:: 3.0
| Added the ``standalone_mode`` parameter.
|
| make_context(self, info_name: 'str | None', args: 'list[str]', parent: 'Context | None' = None, **extra: 't.Any') -> 'Context'
| This function when given an info name and arguments will kick
| off the parsing and create a new :class:`Context`. It does not
| invoke the actual command callback though.
|
| To quickly customize the context class used without overriding
| this method, set the :attr:`context_class` attribute.
|
| :param info_name: the info name for this invocation. Generally this
| is the most descriptive name for the script or
| command. For the toplevel script it's usually
| the name of the script, for commands below it's
| the name of the command.
| :param args: the arguments to parse as list of strings.
| :param parent: the parent context if available.
| :param extra: extra keyword arguments forwarded to the context
| constructor.
|
| .. versionchanged:: 8.0
| Added the :attr:`context_class` attribute.
|
| make_parser(self, ctx: 'Context') -> '_OptionParser'
| Creates the underlying option parser for this command.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from click.core.Command:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.core.Command:
|
| context_class = <class 'click.core.Context'>
| The context is a special internal object that holds state relevant
| for the script execution at every single level. It's normally invisible
| to commands unless they opt-in to getting access to it.
|
| The context is useful as it can pass internal objects around and can
| control special execution features such as reading data from
| environment variables.
|
| A context can be used as context manager in which case it will call
| :meth:`close` on teardown.
|
| :param command: the command class for this context.
| :param parent: the parent context.
| :param info_name: the info name for this invocation. Generally this
| is the most descriptive name for the script or
| command. For the toplevel script it is usually
| the name of the script, for commands below that it's
| the name of the script.
| :param obj: an arbitrary object of user data.
| :param auto_envvar_prefix: the prefix to use for automatic environment
| variables. If this is `None` then reading
| from environment variables is disabled. This
| does not affect manually set environment
| variables which are always read.
| :param default_map: a dictionary (like object) with default values
| for parameters.
| :param terminal_width: the width of the terminal. The default is
| inherit from parent context. If no context
| defines the terminal width then auto
| detection will be applied.
| :param max_content_width: the maximum width for content rendered by
| Click (this currently only affects help
| pages). This defaults to 80 characters if
| not overridden. In other words: even if the
| terminal is larger than that, Click will not
| format things wider than 80 characters by
| default. In addition to that, formatters might
| add some safety mapping on the right.
| :param resilient_parsing: if this flag is enabled then Click will
| parse without any interactivity or callback
| invocation. Default values will also be
| ignored. This is useful for implementing
| things such as completion support.
| :param allow_extra_args: if this is set to `True` then extra arguments
| at the end will not raise an error and will be
| kept on the context. The default is to inherit
| from the command.
| :param allow_interspersed_args: if this is set to `False` then options
| and arguments cannot be mixed. The
| default is to inherit from the command.
| :param ignore_unknown_options: instructs click to ignore options it does
| not know and keeps them for later
| processing.
| :param help_option_names: optionally a list of strings that define how
| the default help parameter is named. The
| default is ``['--help']``.
| :param token_normalize_func: an optional function that is used to
| normalize tokens (options, choices,
| etc.). This for instance can be used to
| implement case insensitive behavior.
| :param color: controls if the terminal supports ANSI colors or not. The
| default is autodetection. This is only needed if ANSI
| codes are used in texts that Click prints which is by
| default not the case. This for instance would affect
| help output.
| :param show_default: Show the default value for commands. If this
| value is not set, it defaults to the value from the parent
| context. ``Command.show_default`` overrides this default for the
| specific command.
|
| .. versionchanged:: 8.2
| The ``protected_args`` attribute is deprecated and will be removed in
| Click 9.0. ``args`` will contain remaining unparsed tokens.
|
| .. versionchanged:: 8.1
| The ``show_default`` parameter is overridden by
| ``Command.show_default``, instead of the other way around.
|
| .. versionchanged:: 8.0
| The ``show_default`` parameter defaults to the value from the
| parent context.
|
| .. versionchanged:: 7.1
| Added the ``show_default`` parameter.
|
| .. versionchanged:: 4.0
| Added the ``color``, ``ignore_unknown_options``, and
| ``max_content_width`` parameters.
|
| .. versionchanged:: 3.0
| Added the ``allow_extra_args`` and ``allow_interspersed_args``
| parameters.
|
| .. versionchanged:: 2.0
| Added the ``resilient_parsing``, ``help_option_names``, and
| ``token_normalize_func`` parameters.
|
|
| ignore_unknown_options = False
class CertParamType(click.types.ParamType)
| CertParamType() -> 'None'
|
| Click option type for the ``--cert`` option. Allows either an
| existing file, the string ``'adhoc'``, or an import for a
| :class:`~ssl.SSLContext` object.
|
| Method resolution order:
| CertParamType
| click.types.ParamType
| typing.Generic
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| convert(self, value: 't.Any', param: 'click.Parameter | None', ctx: 'click.Context | None') -> 't.Any'
| Convert the value to the correct type. This is not called if
| the value is ``None`` (the missing value).
|
| This must accept string values from the command line, as well as
| values that are already the correct type. It may also convert
| other compatible types.
|
| The ``param`` and ``ctx`` arguments may be ``None`` in certain
| situations, such as when converting prompt input.
|
| If the value cannot be converted, call :meth:`fail` with a
| descriptive message.
|
| :param value: The value to convert.
| :param param: The parameter that is using this type to convert
| its value. May be ``None``.
| :param ctx: The current context that arrived at this value. May
| be ``None``.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __parameters__ = ()
|
| name = 'path'
|
| ----------------------------------------------------------------------
| Methods inherited from click.types.ParamType:
|
| __call__(self, value: 't.Any', param: 'Parameter | None' = None, ctx: 'Context | None' = None) -> '_ValueT_co | None'
| Call self as a function.
|
| fail(self, message: 'str', param: 'Parameter | None' = None, ctx: 'Context | None' = None) -> 't.NoReturn'
| Helper method to fail with an invalid value message.
|
| get_metavar(self, param: 'Parameter', ctx: 'Context') -> 'str | None'
| Returns the metavar default for this param if it provides one.
|
| get_missing_message(self, param: 'Parameter', ctx: 'Context | None') -> 'str | None'
| Optionally might return extra information about a missing
| parameter.
|
| .. versionadded:: 2.0
|
| shell_complete(self, ctx: 'Context', param: 'Parameter', incomplete: 'str') -> 'list[CompletionItem]'
| Return a list of
| :class:`~click.shell_completion.CompletionItem` objects for the
| incomplete value. Most types do not provide completions, but
| some do, and this allows custom types to provide custom
| completions as well.
|
| :param ctx: Invocation context for this command.
| :param param: The parameter that is requesting completion.
| :param incomplete: Value being completed. May be empty.
|
| .. versionadded:: 8.0
|
| split_envvar_value(self, rv: 'str') -> 'cabc.Sequence[str]'
| Given a value from an environment variable this splits it up
| into small chunks depending on the defined envvar list splitter.
|
| If the splitter is set to `None`, which means that whitespace splits,
| then leading and trailing whitespace is ignored. Otherwise, leading
| and trailing splitters usually lead to empty items being included.
|
| to_info_dict(self) -> 'ParamTypeInfoDict'
| Gather information that could be useful for a tool generating
| user-facing documentation.
|
| Use :meth:`click.Context.to_info_dict` to traverse the entire
| CLI structure.
|
| .. versionadded:: 8.0
|
| ----------------------------------------------------------------------
| Data descriptors inherited from click.types.ParamType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.types.ParamType:
|
| __orig_bases__ = (typing.Generic[+_ValueT_co], <class 'abc.ABC'>)
|
| arity = 1
|
| envvar_list_splitter = None
|
| is_composite = False
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class FlaskGroup(AppGroup)
| FlaskGroup(add_default_commands: 'bool' = True, create_app: 't.Callable[..., Flask] | None' = None, add_version_option: 'bool' = True, load_dotenv: 'bool' = True, set_debug_flag: 'bool' = True, **extra: 't.Any') -> 'None'
|
| Special subclass of the :class:`AppGroup` group that supports
| loading more commands from the configured Flask app. Normally a
| developer does not have to interface with this class but there are
| some very advanced use cases for which it makes sense to create an
| instance of this. see :ref:`custom-scripts`.
|
| :param add_default_commands: if this is True then the default run and
| shell commands will be added.
| :param add_version_option: adds the ``--version`` option.
| :param create_app: an optional callback that is passed the script info and
| returns the loaded app.
| :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
| files to set environment variables. Will also change the working
| directory to the directory containing the first file found.
| :param set_debug_flag: Set the app's debug flag.
|
| .. versionchanged:: 3.1
| ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files.
|
| .. versionchanged:: 2.2
| Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.
|
| .. versionchanged:: 2.2
| An app context is pushed when running ``app.cli`` commands, so
| ``@with_appcontext`` is no longer required for those commands.
|
| .. versionchanged:: 1.0
| If installed, python-dotenv will be used to load environment variables
| from :file:`.env` and :file:`.flaskenv` files.
|
| Method resolution order:
| FlaskGroup
| AppGroup
| click.core.Group
| click.core.Command
| builtins.object
|
| Methods defined here:
|
| __init__(self, add_default_commands: 'bool' = True, create_app: 't.Callable[..., Flask] | None' = None, add_version_option: 'bool' = True, load_dotenv: 'bool' = True, set_debug_flag: 'bool' = True, **extra: 't.Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| get_command(self, ctx: 'click.Context', name: 'str') -> 'click.Command | None'
| Given a context and a command name, this returns a :class:`Command`
| object if it exists or returns ``None``.
|
| list_commands(self, ctx: 'click.Context') -> 'list[str]'
| Returns a list of subcommand names in the order they should appear.
|
| make_context(self, info_name: 'str | None', args: 'list[str]', parent: 'click.Context | None' = None, **extra: 't.Any') -> 'click.Context'
| This function when given an info name and arguments will kick
| off the parsing and create a new :class:`Context`. It does not
| invoke the actual command callback though.
|
| To quickly customize the context class used without overriding
| this method, set the :attr:`context_class` attribute.
|
| :param info_name: the info name for this invocation. Generally this
| is the most descriptive name for the script or
| command. For the toplevel script it's usually
| the name of the script, for commands below it's
| the name of the command.
| :param args: the arguments to parse as list of strings.
| :param parent: the parent context if available.
| :param extra: extra keyword arguments forwarded to the context
| constructor.
|
| .. versionchanged:: 8.0
| Added the :attr:`context_class` attribute.
|
| parse_args(self, ctx: 'click.Context', args: 'list[str]') -> 'list[str]'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from AppGroup:
|
| command(self, *args: 't.Any', **kwargs: 't.Any') -> 't.Callable[[t.Callable[..., t.Any]], click.Command]'
| This works exactly like the method of the same name on a regular
| :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
| unless it's disabled by passing ``with_appcontext=False``.
|
| group(self, *args: 't.Any', **kwargs: 't.Any') -> 't.Callable[[t.Callable[..., t.Any]], click.Group]'
| This works exactly like the method of the same name on a regular
| :class:`click.Group` but it defaults the group class to
| :class:`AppGroup`.
|
| ----------------------------------------------------------------------
| Methods inherited from click.core.Group:
|
| add_command(self, cmd: 'Command', name: 'str | None' = None) -> 'None'
| Registers another :class:`Command` with this group. If the name
| is not provided, the name of the command is used.
|
| collect_usage_pieces(self, ctx: 'Context') -> 'list[str]'
| Returns all the pieces that go into the usage line and returns
| it as a list of strings.
|
| format_commands(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Extra format methods for multi methods that adds all the commands
| after the options.
|
| format_options(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes all the options into the formatter if they exist.
|
| invoke(self, ctx: 'Context') -> 't.Any'
| Given a context, this invokes the attached callback (if it exists)
| in the right way.
|
| resolve_command(self, ctx: 'Context', args: 'list[str]') -> 'tuple[str | None, Command | None, list[str]]'
|
| result_callback(self, replace: 'bool' = False) -> 't.Callable[[F], F]'
| Adds a result callback to the command. By default if a
| result callback is already registered this will chain them but
| this can be disabled with the `replace` parameter. The result
| callback is invoked with the return value of the subcommand
| (or the list of return values from all subcommands if chaining
| is enabled) as well as the parameters as they would be passed
| to the main callback.
|
| Example::
|
| @click.group()
| @click.option('-i', '--input', default=23)
| def cli(input):
| return 42
|
| @cli.result_callback()
| def process_result(result, input):
| return result + input
|
| :param replace: if set to `True` an already existing result
| callback will be removed.
|
| .. versionchanged:: 8.0
| Renamed from ``resultcallback``.
|
| .. versionadded:: 3.0
|
| shell_complete(self, ctx: 'Context', incomplete: 'str') -> 'list[CompletionItem]'
| Return a list of completions for the incomplete value. Looks
| at the names of options, subcommands, and chained
| multi-commands.
|
| :param ctx: Invocation context for this command.
| :param incomplete: Value being completed. May be empty.
|
| .. versionadded:: 8.0
|
| to_info_dict(self, ctx: 'Context') -> 'dict[str, t.Any]'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.core.Group:
|
| allow_extra_args = True
|
| allow_interspersed_args = False
|
| command_class = None
|
| group_class = None
|
| ----------------------------------------------------------------------
| Methods inherited from click.core.Command:
|
| __call__(self, *args: 't.Any', **kwargs: 't.Any') -> 't.Any'
| Alias for :meth:`main`.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| format_epilog(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the epilog into the formatter if it exists.
|
| format_help(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the help into the formatter if it exists.
|
| This is a low-level method called by :meth:`get_help`.
|
| This calls the following methods:
|
| - :meth:`format_usage`
| - :meth:`format_help_text`
| - :meth:`format_options`
| - :meth:`format_epilog`
|
| format_help_text(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the help text to the formatter if it exists.
|
| format_usage(self, ctx: 'Context', formatter: 'HelpFormatter') -> 'None'
| Writes the usage line into the formatter.
|
| This is a low-level method called by :meth:`get_usage`.
|
| get_help(self, ctx: 'Context') -> 'str'
| Formats the help into a string and returns it.
|
| Calls :meth:`format_help` internally.
|
| get_help_option(self, ctx: 'Context') -> 'Option | None'
| Returns the help option object.
|
| Skipped if :attr:`add_help_option` is ``False``.
|
| .. versionchanged:: 8.1.8
| The help option is now cached to avoid creating it multiple times.
|
| get_help_option_names(self, ctx: 'Context') -> 'list[str]'
| Returns the names for the help option.
|
| get_params(self, ctx: 'Context') -> 'list[Parameter]'
|
| get_short_help_str(self, limit: 'int' = 45) -> 'str'
| Gets short help for the command or makes it by shortening the
| long help string.
|
| get_usage(self, ctx: 'Context') -> 'str'
| Formats the usage line into a string and returns it.
|
| Calls :meth:`format_usage` internally.
|
| main(self, args: 'cabc.Sequence[str] | None' = None, prog_name: 'str | None' = None, complete_var: 'str | None' = None, standalone_mode: 'bool' = True, windows_expand_args: 'bool' = True, **extra: 't.Any') -> 't.Any'
| This is the way to invoke a script with all the bells and
| whistles as a command line application. This will always terminate
| the application after a call. If this is not wanted, ``SystemExit``
| needs to be caught.
|
| This method is also available by directly calling the instance of
| a :class:`Command`.
|
| :param args: the arguments that should be used for parsing. If not
| provided, ``sys.argv[1:]`` is used.
| :param prog_name: the program name that should be used. By default
| the program name is constructed by taking the file
| name from ``sys.argv[0]``.
| :param complete_var: the environment variable that controls the
| bash completion support. The default is
| ``"_<prog_name>_COMPLETE"`` with prog_name in
| uppercase.
| :param standalone_mode: the default behavior is to invoke the script
| in standalone mode. Click will then
| handle exceptions and convert them into
| error messages and the function will never
| return but shut down the interpreter. If
| this is set to `False` they will be
| propagated to the caller and the return
| value of this function is the return value
| of :meth:`invoke`.
| :param windows_expand_args: Expand glob patterns, user dir, and
| env vars in command line args on Windows.
| :param extra: extra keyword arguments are forwarded to the context
| constructor. See :class:`Context` for more information.
|
| .. versionchanged:: 8.0.1
| Added the ``windows_expand_args`` parameter to allow
| disabling command line arg expansion on Windows.
|
| .. versionchanged:: 8.0
| When taking arguments from ``sys.argv`` on Windows, glob
| patterns, user dir, and env vars are expanded.
|
| .. versionchanged:: 3.0
| Added the ``standalone_mode`` parameter.
|
| make_parser(self, ctx: 'Context') -> '_OptionParser'
| Creates the underlying option parser for this command.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from click.core.Command:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.core.Command:
|
| context_class = <class 'click.core.Context'>
| The context is a special internal object that holds state relevant
| for the script execution at every single level. It's normally invisible
| to commands unless they opt-in to getting access to it.
|
| The context is useful as it can pass internal objects around and can
| control special execution features such as reading data from
| environment variables.
|
| A context can be used as context manager in which case it will call
| :meth:`close` on teardown.
|
| :param command: the command class for this context.
| :param parent: the parent context.
| :param info_name: the info name for this invocation. Generally this
| is the most descriptive name for the script or
| command. For the toplevel script it is usually
| the name of the script, for commands below that it's
| the name of the script.
| :param obj: an arbitrary object of user data.
| :param auto_envvar_prefix: the prefix to use for automatic environment
| variables. If this is `None` then reading
| from environment variables is disabled. This
| does not affect manually set environment
| variables which are always read.
| :param default_map: a dictionary (like object) with default values
| for parameters.
| :param terminal_width: the width of the terminal. The default is
| inherit from parent context. If no context
| defines the terminal width then auto
| detection will be applied.
| :param max_content_width: the maximum width for content rendered by
| Click (this currently only affects help
| pages). This defaults to 80 characters if
| not overridden. In other words: even if the
| terminal is larger than that, Click will not
| format things wider than 80 characters by
| default. In addition to that, formatters might
| add some safety mapping on the right.
| :param resilient_parsing: if this flag is enabled then Click will
| parse without any interactivity or callback
| invocation. Default values will also be
| ignored. This is useful for implementing
| things such as completion support.
| :param allow_extra_args: if this is set to `True` then extra arguments
| at the end will not raise an error and will be
| kept on the context. The default is to inherit
| from the command.
| :param allow_interspersed_args: if this is set to `False` then options
| and arguments cannot be mixed. The
| default is to inherit from the command.
| :param ignore_unknown_options: instructs click to ignore options it does
| not know and keeps them for later
| processing.
| :param help_option_names: optionally a list of strings that define how
| the default help parameter is named. The
| default is ``['--help']``.
| :param token_normalize_func: an optional function that is used to
| normalize tokens (options, choices,
| etc.). This for instance can be used to
| implement case insensitive behavior.
| :param color: controls if the terminal supports ANSI colors or not. The
| default is autodetection. This is only needed if ANSI
| codes are used in texts that Click prints which is by
| default not the case. This for instance would affect
| help output.
| :param show_default: Show the default value for commands. If this
| value is not set, it defaults to the value from the parent
| context. ``Command.show_default`` overrides this default for the
| specific command.
|
| .. versionchanged:: 8.2
| The ``protected_args`` attribute is deprecated and will be removed in
| Click 9.0. ``args`` will contain remaining unparsed tokens.
|
| .. versionchanged:: 8.1
| The ``show_default`` parameter is overridden by
| ``Command.show_default``, instead of the other way around.
|
| .. versionchanged:: 8.0
| The ``show_default`` parameter defaults to the value from the
| parent context.
|
| .. versionchanged:: 7.1
| Added the ``show_default`` parameter.
|
| .. versionchanged:: 4.0
| Added the ``color``, ``ignore_unknown_options``, and
| ``max_content_width`` parameters.
|
| .. versionchanged:: 3.0
| Added the ``allow_extra_args`` and ``allow_interspersed_args``
| parameters.
|
| .. versionchanged:: 2.0
| Added the ``resilient_parsing``, ``help_option_names``, and
| ``token_normalize_func`` parameters.
|
|
| ignore_unknown_options = False
class NoAppException(click.exceptions.UsageError)
| NoAppException(message: 'str', ctx: 'Context | None' = None) -> 'None'
|
| Raised if an application cannot be found or loaded.
|
| Method resolution order:
| NoAppException
| click.exceptions.UsageError
| click.exceptions.ClickException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from click.exceptions.UsageError:
|
| __init__(self, message: 'str', ctx: 'Context | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| show(self, file: 't.IO[t.Any] | None' = None) -> 'None'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.exceptions.UsageError:
|
| exit_code = 2
|
| ----------------------------------------------------------------------
| Methods inherited from click.exceptions.ClickException:
|
| __str__(self) -> 'str'
| Return str(self).
|
| format_message(self) -> 'str'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from click.exceptions.ClickException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ScriptInfo(builtins.object)
| ScriptInfo(app_import_path: 'str | None' = None, create_app: 't.Callable[..., Flask] | None' = None, set_debug_flag: 'bool' = True, load_dotenv_defaults: 'bool' = True) -> 'None'
|
| Helper object to deal with Flask applications. This is usually not
| necessary to interface with as it's used internally in the dispatching
| to click. In future versions of Flask this object will most likely play
| a bigger role. Typically it's created automatically by the
| :class:`FlaskGroup` but you can also manually create it and pass it
| onwards as click object.
|
| .. versionchanged:: 3.1
| Added the ``load_dotenv_defaults`` parameter and attribute.
|
| Methods defined here:
|
| __init__(self, app_import_path: 'str | None' = None, create_app: 't.Callable[..., Flask] | None' = None, set_debug_flag: 'bool' = True, load_dotenv_defaults: 'bool' = True) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| load_app(self) -> 'Flask'
| Loads the Flask app (if not yet loaded) and returns it. Calling
| this multiple times will just result in the already loaded app to
| be returned.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class SeparatedPathType(click.types.Path)
| SeparatedPathType(exists: 'bool' = False, file_okay: 'bool' = True, dir_okay: 'bool' = True, writable: 'bool' = False, readable: 'bool' = True, resolve_path: 'bool' = False, allow_dash: 'bool' = False, path_type: 'type | None' = None, executable: 'bool' = False) -> 'None'
|
| Click option type that accepts a list of values separated by the
| OS's path separator (``:``, ``;`` on Windows). Each value is
| validated as a :class:`click.Path` type.
|
| Method resolution order:
| SeparatedPathType
| click.types.Path
| click.types.ParamType
| typing.Generic
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| convert(self, value: 't.Any', param: 'click.Parameter | None', ctx: 'click.Context | None') -> 't.Any'
| Convert the value to the correct type. This is not called if
| the value is ``None`` (the missing value).
|
| This must accept string values from the command line, as well as
| values that are already the correct type. It may also convert
| other compatible types.
|
| The ``param`` and ``ctx`` arguments may be ``None`` in certain
| situations, such as when converting prompt input.
|
| If the value cannot be converted, call :meth:`fail` with a
| descriptive message.
|
| :param value: The value to convert.
| :param param: The parameter that is using this type to convert
| its value. May be ``None``.
| :param ctx: The current context that arrived at this value. May
| be ``None``.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from click.types.Path:
|
| __init__(self, exists: 'bool' = False, file_okay: 'bool' = True, dir_okay: 'bool' = True, writable: 'bool' = False, readable: 'bool' = True, resolve_path: 'bool' = False, allow_dash: 'bool' = False, path_type: 'type | None' = None, executable: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| coerce_path_result(self, value: 'str | os.PathLike[str]') -> 'str | bytes | os.PathLike[str]'
|
| shell_complete(self, ctx: 'Context', param: 'Parameter', incomplete: 'str') -> 'list[CompletionItem]'
| Return a special completion marker that tells the completion
| system to use the shell to provide path completions for only
| directories or any paths.
|
| :param ctx: Invocation context for this command.
| :param param: The parameter that is requesting completion.
| :param incomplete: Value being completed. May be empty.
|
| .. versionadded:: 8.0
|
| to_info_dict(self) -> 'PathInfoDict'
| Gather information that could be useful for a tool generating
| user-facing documentation.
|
| Use :meth:`click.Context.to_info_dict` to traverse the entire
| CLI structure.
|
| .. versionadded:: 8.0
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.types.Path:
|
| __orig_bases__ = (click.types.ParamType[str | bytes | os.PathLike[str]...
|
| envvar_list_splitter = ';'
|
| ----------------------------------------------------------------------
| Methods inherited from click.types.ParamType:
|
| __call__(self, value: 't.Any', param: 'Parameter | None' = None, ctx: 'Context | None' = None) -> '_ValueT_co | None'
| Call self as a function.
|
| fail(self, message: 'str', param: 'Parameter | None' = None, ctx: 'Context | None' = None) -> 't.NoReturn'
| Helper method to fail with an invalid value message.
|
| get_metavar(self, param: 'Parameter', ctx: 'Context') -> 'str | None'
| Returns the metavar default for this param if it provides one.
|
| get_missing_message(self, param: 'Parameter', ctx: 'Context | None') -> 'str | None'
| Optionally might return extra information about a missing
| parameter.
|
| .. versionadded:: 2.0
|
| split_envvar_value(self, rv: 'str') -> 'cabc.Sequence[str]'
| Given a value from an environment variable this splits it up
| into small chunks depending on the defined envvar list splitter.
|
| If the splitter is set to `None`, which means that whitespace splits,
| then leading and trailing whitespace is ignored. Otherwise, leading
| and trailing splitters usually lead to empty items being included.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from click.types.ParamType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from click.types.ParamType:
|
| arity = 1
|
| is_composite = False
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
FUNCTIONS
find_app_by_string(module: 'ModuleType', app_name: 'str') -> 'Flask'
Check if the given string is a variable name or a function. Call
a function to get the app instance, or return the variable directly.
find_best_app(module: 'ModuleType') -> 'Flask'
Given a module instance this tries to find the best possible
application in the module or raises an exception.
get_version(ctx: 'click.Context', param: 'click.Parameter', value: 't.Any') -> 'None'
load_dotenv(path: 'str | os.PathLike[str] | None' = None, load_defaults: 'bool' = True) -> 'bool'
Load "dotenv" files to set environment variables. A given path takes
precedence over ``.env``, which takes precedence over ``.flaskenv``. After
loading and combining these files, values are only set if the key is not
already set in ``os.environ``.
This is a no-op if `python-dotenv`_ is not installed.
.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
:param path: Load the file at this location.
:param load_defaults: Search for and load the default ``.flaskenv`` and
``.env`` files.
:return: ``True`` if at least one env var was loaded.
.. versionchanged:: 3.1
Added the ``load_defaults`` parameter. A given path takes precedence
over default files.
.. versionchanged:: 2.0
The current directory is not changed to the location of the
loaded file.
.. versionchanged:: 2.0
When loading the env files, set the default encoding to UTF-8.
.. versionchanged:: 1.1.0
Returns ``False`` when python-dotenv is not installed, or when
the given path isn't a file.
.. versionadded:: 1.0
locate_app(module_name: 'str', app_name: 'str | None', raise_if_not_found: 'bool' = True) -> 'Flask | None'
main() -> 'None'
prepare_import(path: 'str') -> 'str'
Given a filename this will try to calculate the python path, add it
to the search path and return the actual module name that is expected.
show_server_banner(debug: 'bool', app_import_path: 'str | None') -> 'None'
Show extra startup messages the first time the server is run,
ignoring the reloader.
with_appcontext(f: 'F') -> 'F'
Wraps a callback so that it's guaranteed to be executed with the
script's application context.
Custom commands (and their options) registered under ``app.cli`` or
``blueprint.cli`` will always have an app context available, this
decorator is not required in that case.
.. versionchanged:: 2.2
The app context is active for subcommands as well as the
decorated callback. The app context is always available to
``app.cli`` command and parameter callbacks.
DATA
F = ~F
cli = <FlaskGroup flask>
current_app = <LocalProxy unbound>
routes_command = <Command routes>
Show all registered routes with endpoints and methods.
run_command = <Command run>
Run a local development server.
This server is for development purposes only. It does not provide
the stability, security, or performance of production WSGI servers.
The reloader and debugger are enabled by default with the '--debug'
option.
shell_command = <Command shell>
Run an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to its configuration.
This is useful for executing small snippets of management code
without having to manually configure the application.
version_option = <Option version>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\cli.py
flask.config
Python Library Documentation: module flask.config in flask
NAME
flask.config
CLASSES
builtins.dict(builtins.object)
Config
typing.Generic(builtins.object)
ConfigAttribute
class Config(builtins.dict)
| Config(root_path: 'str | os.PathLike[str]', defaults: 'dict[str, t.Any] | None' = None) -> 'None'
|
| Works exactly like a dict but provides ways to fill it from files
| or special dictionaries. There are two common patterns to populate the
| config.
|
| Either you can fill the config from a config file::
|
| app.config.from_pyfile('yourconfig.cfg')
|
| Or alternatively you can define the configuration options in the
| module that calls :meth:`from_object` or provide an import path to
| a module that should be loaded. It is also possible to tell it to
| use the same module and with that provide the configuration values
| just before the call::
|
| DEBUG = True
| SECRET_KEY = 'development key'
| app.config.from_object(__name__)
|
| In both cases (loading from any Python file or loading from modules),
| only uppercase keys are added to the config. This makes it possible to use
| lowercase values in the config file for temporary values that are not added
| to the config or to define the config keys in the same file that implements
| the application.
|
| Probably the most interesting way to load configurations is from an
| environment variable pointing to a file::
|
| app.config.from_envvar('YOURAPPLICATION_SETTINGS')
|
| In this case before launching the application you have to set this
| environment variable to the file you want to use. On Linux and OS X
| use the export statement::
|
| export YOURAPPLICATION_SETTINGS='/path/to/config/file'
|
| On windows use `set` instead.
|
| :param root_path: path to which files are read relative from. When the
| config object is created by the application, this is
| the application's :attr:`~flask.Flask.root_path`.
| :param defaults: an optional dictionary of default values
|
| Method resolution order:
| Config
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __init__(self, root_path: 'str | os.PathLike[str]', defaults: 'dict[str, t.Any] | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| from_envvar(self, variable_name: 'str', silent: 'bool' = False) -> 'bool'
| Loads a configuration from an environment variable pointing to
| a configuration file. This is basically just a shortcut with nicer
| error messages for this line of code::
|
| app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
|
| :param variable_name: name of the environment variable
| :param silent: set to ``True`` if you want silent failure for missing
| files.
| :return: ``True`` if the file was loaded successfully.
|
| from_file(self, filename: 'str | os.PathLike[str]', load: 't.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]]', silent: 'bool' = False, text: 'bool' = True) -> 'bool'
| Update the values in the config from a file that is loaded
| using the ``load`` parameter. The loaded data is passed to the
| :meth:`from_mapping` method.
|
| .. code-block:: python
|
| import json
| app.config.from_file("config.json", load=json.load)
|
| import tomllib
| app.config.from_file("config.toml", load=tomllib.load, text=False)
|
| :param filename: The path to the data file. This can be an
| absolute path or relative to the config root path.
| :param load: A callable that takes a file handle and returns a
| mapping of loaded data from the file.
| :type load: ``Callable[[Reader], Mapping]`` where ``Reader``
| implements a ``read`` method.
| :param silent: Ignore the file if it doesn't exist.
| :param text: Open the file in text or binary mode.
| :return: ``True`` if the file was loaded successfully.
|
| .. versionchanged:: 2.3
| The ``text`` parameter was added.
|
| .. versionadded:: 2.0
|
| from_mapping(self, mapping: 't.Mapping[str, t.Any] | None' = None, **kwargs: 't.Any') -> 'bool'
| Updates the config like :meth:`update` ignoring items with
| non-upper keys.
|
| :return: Always returns ``True``.
|
| .. versionadded:: 0.11
|
| from_object(self, obj: 'object | str') -> 'None'
| Updates the values from the given object. An object can be of one
| of the following two types:
|
| - a string: in this case the object with that name will be imported
| - an actual object reference: that object is used directly
|
| Objects are usually either modules or classes. :meth:`from_object`
| loads only the uppercase attributes of the module/class. A ``dict``
| object will not work with :meth:`from_object` because the keys of a
| ``dict`` are not attributes of the ``dict`` class.
|
| Example of module-based configuration::
|
| app.config.from_object('yourapplication.default_config')
| from yourapplication import default_config
| app.config.from_object(default_config)
|
| Nothing is done to the object before loading. If the object is a
| class and has ``@property`` attributes, it needs to be
| instantiated before being passed to this method.
|
| You should not use this function to load the actual configuration but
| rather configuration defaults. The actual config should be loaded
| with :meth:`from_pyfile` and ideally from a location not within the
| package because the package might be installed system wide.
|
| See :ref:`config-dev-prod` for an example of class-based configuration
| using :meth:`from_object`.
|
| :param obj: an import name or object
|
| from_prefixed_env(self, prefix: 'str' = 'FLASK', *, loads: 't.Callable[[str], t.Any]' = <function loads at 0x0000023206713560>) -> 'bool'
| Load any environment variables that start with ``FLASK_``,
| dropping the prefix from the env key for the config key. Values
| are passed through a loading function to attempt to convert them
| to more specific types than strings.
|
| Keys are loaded in :func:`sorted` order.
|
| The default loading function attempts to parse values as any
| valid JSON type, including dicts and lists.
|
| Specific items in nested dicts can be set by separating the
| keys with double underscores (``__``). If an intermediate key
| doesn't exist, it will be initialized to an empty dict.
|
| :param prefix: Load env vars that start with this prefix,
| separated with an underscore (``_``).
| :param loads: Pass each string value to this function and use
| the returned value as the config value. If any error is
| raised it is ignored and the value remains a string. The
| default is :func:`json.loads`.
|
| .. versionadded:: 2.1
|
| from_pyfile(self, filename: 'str | os.PathLike[str]', silent: 'bool' = False) -> 'bool'
| Updates the values in the config from a Python file. This function
| behaves as if the file was imported as module with the
| :meth:`from_object` function.
|
| :param filename: the filename of the config. This can either be an
| absolute filename or a filename relative to the
| root path.
| :param silent: set to ``True`` if you want silent failure for missing
| files.
| :return: ``True`` if the file was loaded successfully.
|
| .. versionadded:: 0.7
| `silent` parameter.
|
| get_namespace(self, namespace: 'str', lowercase: 'bool' = True, trim_namespace: 'bool' = True) -> 'dict[str, t.Any]'
| Returns a dictionary containing a subset of configuration options
| that match the specified namespace/prefix. Example usage::
|
| app.config['IMAGE_STORE_TYPE'] = 'fs'
| app.config['IMAGE_STORE_PATH'] = '/var/app/images'
| app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
| image_store_config = app.config.get_namespace('IMAGE_STORE_')
|
| The resulting dictionary `image_store_config` would look like::
|
| {
| 'type': 'fs',
| 'path': '/var/app/images',
| 'base_url': 'http://img.website.com'
| }
|
| This is often useful when configuration options map directly to
| keyword arguments in functions or class constructors.
|
| :param namespace: a configuration namespace
| :param lowercase: a flag indicating if the keys of the resulting
| dictionary should be lowercase
| :param trim_namespace: a flag indicating if the keys of the resulting
| dictionary should not include the namespace
|
| .. versionadded:: 0.11
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from builtins.dict:
|
| __hash__ = None
class ConfigAttribute(typing.Generic)
| ConfigAttribute(name: 'str', get_converter: 't.Callable[[t.Any], T] | None' = None) -> 'None'
|
| Makes an attribute forward to the config
|
| Method resolution order:
| ConfigAttribute
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __get__(self, obj: 'App | None', owner: 'type[App] | None' = None) -> 'T | te.Self'
|
| __init__(self, name: 'str', get_converter: 't.Callable[[t.Any], T] | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __set__(self, obj: 'App', value: 't.Any') -> 'None'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~T],)
|
| __parameters__ = (~T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
DATA
T = ~T
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\config.py
flask.copy_current_request_context
Python Library Documentation: function copy_current_request_context in module flask.ctx
copy_current_request_context(f: 'F') -> 'F'
A helper function that decorates a function to retain the current
request context. This is useful when working with greenlets. The moment
the function is decorated a copy of the request context is created and
then pushed when the function is called. The current session is also
included in the copied request context.
Example::
import gevent
from flask import copy_current_request_context
@app.route('/')
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request or
# flask.session like you would otherwise in the view function.
...
gevent.spawn(do_some_work)
return 'Regular response'
.. versionadded:: 0.10
flask.ctx
Python Library Documentation: module flask.ctx in flask
NAME
flask.ctx
CLASSES
builtins.object
AppContext
RequestContext
class AppContext(builtins.object)
| AppContext(app: 'Flask') -> 'None'
|
| The app context contains application-specific information. An app
| context is created and pushed at the beginning of each request if
| one is not already active. An app context is also pushed when
| running CLI commands.
|
| Methods defined here:
|
| __enter__(self) -> 'AppContext'
|
| __exit__(self, exc_type: 'type | None', exc_value: 'BaseException | None', tb: 'TracebackType | None') -> 'None'
|
| __init__(self, app: 'Flask') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| pop(self, exc: 'BaseException | None' = <object object at 0x00000232059594E0>) -> 'None'
| Pops the app context.
|
| push(self) -> 'None'
| Binds the app context to the current context.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class RequestContext(builtins.object)
| RequestContext(app: 'Flask', environ: 'WSGIEnvironment', request: 'Request | None' = None, session: 'SessionMixin | None' = None) -> 'None'
|
| The request context contains per-request information. The Flask
| app creates and pushes it at the beginning of the request, then pops
| it at the end of the request. It will create the URL adapter and
| request object for the WSGI environment provided.
|
| Do not attempt to use this class directly, instead use
| :meth:`~flask.Flask.test_request_context` and
| :meth:`~flask.Flask.request_context` to create this object.
|
| When the request context is popped, it will evaluate all the
| functions registered on the application for teardown execution
| (:meth:`~flask.Flask.teardown_request`).
|
| The request context is automatically popped at the end of the
| request. When using the interactive debugger, the context will be
| restored so ``request`` is still accessible. Similarly, the test
| client can preserve the context after the request ends. However,
| teardown functions may already have closed some resources such as
| database connections.
|
| Methods defined here:
|
| __enter__(self) -> 'RequestContext'
|
| __exit__(self, exc_type: 'type | None', exc_value: 'BaseException | None', tb: 'TracebackType | None') -> 'None'
|
| __init__(self, app: 'Flask', environ: 'WSGIEnvironment', request: 'Request | None' = None, session: 'SessionMixin | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| copy(self) -> 'RequestContext'
| Creates a copy of this request context with the same request object.
| This can be used to move a request context to a different greenlet.
| Because the actual request object is the same this cannot be used to
| move a request context to a different thread unless access to the
| request object is locked.
|
| .. versionadded:: 0.10
|
| .. versionchanged:: 1.1
| The current session object is used instead of reloading the original
| data. This prevents `flask.session` pointing to an out-of-date object.
|
| match_request(self) -> 'None'
| Can be overridden by a subclass to hook into the matching
| of the request.
|
| pop(self, exc: 'BaseException | None' = <object object at 0x00000232059594E0>) -> 'None'
| Pops the request context and unbinds it by doing that. This will
| also trigger the execution of functions registered by the
| :meth:`~flask.Flask.teardown_request` decorator.
|
| .. versionchanged:: 0.9
| Added the `exc` argument.
|
| push(self) -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| session
| The session data associated with this request. Not available until
| this context has been pushed. Accessing this property, also accessed by
| the :data:`~flask.session` proxy, sets :attr:`.SessionMixin.accessed`.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
after_this_request(f: 'ft.AfterRequestCallable[t.Any]') -> 'ft.AfterRequestCallable[t.Any]'
Executes a function after this request. This is useful to modify
response objects. The function is passed the response object and has
to return the same or a new one.
Example::
@app.route('/')
def index():
@after_this_request
def add_header(response):
response.headers['X-Foo'] = 'Parachute'
return response
return 'Hello World!'
This is more useful if a function other than the view function wants to
modify a response. For instance think of a decorator that wants to add
some headers without converting the return value into a response object.
.. versionadded:: 0.9
copy_current_request_context(f: 'F') -> 'F'
A helper function that decorates a function to retain the current
request context. This is useful when working with greenlets. The moment
the function is decorated a copy of the request context is created and
then pushed when the function is called. The current session is also
included in the copied request context.
Example::
import gevent
from flask import copy_current_request_context
@app.route('/')
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request or
# flask.session like you would otherwise in the view function.
...
gevent.spawn(do_some_work)
return 'Regular response'
.. versionadded:: 0.10
has_app_context() -> 'bool'
Works like :func:`has_request_context` but for the application
context. You can also just do a boolean check on the
:data:`current_app` object instead.
.. versionadded:: 0.9
has_request_context() -> 'bool'
If you have code that wants to test if a request context is there or
not this function can be used. For instance, you may want to take advantage
of request information if the request object is available, but fail
silently if it is unavailable.
::
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and has_request_context():
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Alternatively you can also just test any of the context bound objects
(such as :class:`request` or :class:`g`) for truthness::
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and request:
remote_addr = request.remote_addr
self.remote_addr = remote_addr
.. versionadded:: 0.7
DATA
F = ~F
appcontext_popped = <blinker.base.NamedSignal object at 0x000002320849...
appcontext_pushed = <blinker.base.NamedSignal object at 0x000002320849...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\ctx.py
flask.current_app
Error rendering doc: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). See the documentation for more information.
flask.flash
Python Library Documentation: function flash in module flask.helpers
flash(message: 'str', category: 'str' = 'message') -> 'None'
Flashes a message to the next request. In order to remove the
flashed message from the session and to display it to the user,
the template has to call :func:`get_flashed_messages`.
.. versionchanged:: 0.3
`category` parameter added.
:param message: the message to be flashed.
:param category: the category for the message. The following values
are recommended: ``'message'`` for any kind of message,
``'error'`` for errors, ``'info'`` for information
messages and ``'warning'`` for warnings. However any
kind of string can be used as category.
flask.g
Error rendering doc: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). See the documentation for more information.
flask.get_flashed_messages
Python Library Documentation: function get_flashed_messages in module flask.helpers
get_flashed_messages(with_categories: 'bool' = False, category_filter: 't.Iterable[str]' = ()) -> 'list[str] | list[tuple[str, str]]'
Pulls all flashed messages from the session and returns them.
Further calls in the same request to the function will return
the same messages. By default just the messages are returned,
but when `with_categories` is set to ``True``, the return value will
be a list of tuples in the form ``(category, message)`` instead.
Filter the flashed messages to one or more categories by providing those
categories in `category_filter`. This allows rendering categories in
separate html blocks. The `with_categories` and `category_filter`
arguments are distinct:
* `with_categories` controls whether categories are returned with message
text (``True`` gives a tuple, where ``False`` gives just the message text).
* `category_filter` filters the messages down to only those matching the
provided categories.
See :doc:`/patterns/flashing` for examples.
.. versionchanged:: 0.3
`with_categories` parameter added.
.. versionchanged:: 0.9
`category_filter` parameter added.
:param with_categories: set to ``True`` to also receive categories.
:param category_filter: filter of categories to limit return values. Only
categories in the list will be returned.
flask.get_template_attribute
Python Library Documentation: function get_template_attribute in module flask.helpers
get_template_attribute(template_name: 'str', attribute: 'str') -> 't.Any'
Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named :file:`_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this::
hello = get_template_attribute('_cider.html', 'hello')
return hello('World')
.. versionadded:: 0.2
:param template_name: the name of the template
:param attribute: the name of the variable of macro to access
flask.globals
Python Library Documentation: module flask.globals in flask
NAME
flask.globals
DATA
__annotations__ = {'_cv_app': 'ContextVar[AppContext]', '_cv_request':...
app_ctx = <LocalProxy unbound>
current_app = <LocalProxy unbound>
g = <LocalProxy unbound>
request = <LocalProxy unbound>
request_ctx = <LocalProxy unbound>
session = <LocalProxy unbound>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\globals.py
flask.got_request_exception
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.has_app_context
Python Library Documentation: function has_app_context in module flask.ctx
has_app_context() -> 'bool'
Works like :func:`has_request_context` but for the application
context. You can also just do a boolean check on the
:data:`current_app` object instead.
.. versionadded:: 0.9
flask.has_request_context
Python Library Documentation: function has_request_context in module flask.ctx
has_request_context() -> 'bool'
If you have code that wants to test if a request context is there or
not this function can be used. For instance, you may want to take advantage
of request information if the request object is available, but fail
silently if it is unavailable.
::
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and has_request_context():
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Alternatively you can also just test any of the context bound objects
(such as :class:`request` or :class:`g`) for truthness::
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and request:
remote_addr = request.remote_addr
self.remote_addr = remote_addr
.. versionadded:: 0.7
flask.helpers
Python Library Documentation: module flask.helpers in flask
NAME
flask.helpers
FUNCTIONS
abort(code: 'int | BaseResponse', *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given
status code.
If :data:`~flask.current_app` is available, it will call its
:attr:`~flask.Flask.aborter` object, otherwise it will use
:func:`werkzeug.exceptions.abort`.
:param code: The status code for the exception, which must be
registered in ``app.aborter``.
:param args: Passed to the exception.
:param kwargs: Passed to the exception.
.. versionadded:: 2.2
Calls ``current_app.aborter`` if available instead of always
using Werkzeug's default ``abort``.
flash(message: 'str', category: 'str' = 'message') -> 'None'
Flashes a message to the next request. In order to remove the
flashed message from the session and to display it to the user,
the template has to call :func:`get_flashed_messages`.
.. versionchanged:: 0.3
`category` parameter added.
:param message: the message to be flashed.
:param category: the category for the message. The following values
are recommended: ``'message'`` for any kind of message,
``'error'`` for errors, ``'info'`` for information
messages and ``'warning'`` for warnings. However any
kind of string can be used as category.
get_debug_flag() -> 'bool'
Get whether debug mode should be enabled for the app, indicated by the
:envvar:`FLASK_DEBUG` environment variable. The default is ``False``.
get_flashed_messages(with_categories: 'bool' = False, category_filter: 't.Iterable[str]' = ()) -> 'list[str] | list[tuple[str, str]]'
Pulls all flashed messages from the session and returns them.
Further calls in the same request to the function will return
the same messages. By default just the messages are returned,
but when `with_categories` is set to ``True``, the return value will
be a list of tuples in the form ``(category, message)`` instead.
Filter the flashed messages to one or more categories by providing those
categories in `category_filter`. This allows rendering categories in
separate html blocks. The `with_categories` and `category_filter`
arguments are distinct:
* `with_categories` controls whether categories are returned with message
text (``True`` gives a tuple, where ``False`` gives just the message text).
* `category_filter` filters the messages down to only those matching the
provided categories.
See :doc:`/patterns/flashing` for examples.
.. versionchanged:: 0.3
`with_categories` parameter added.
.. versionchanged:: 0.9
`category_filter` parameter added.
:param with_categories: set to ``True`` to also receive categories.
:param category_filter: filter of categories to limit return values. Only
categories in the list will be returned.
get_load_dotenv(default: 'bool' = True) -> 'bool'
Get whether the user has disabled loading default dotenv files by
setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load
the files.
:param default: What to return if the env var isn't set.
get_root_path(import_name: 'str') -> 'str'
Find the root path of a package, or the path that contains a
module. If it cannot be found, returns the current working
directory.
Not to be confused with the value returned by :func:`find_package`.
:meta private:
get_template_attribute(template_name: 'str', attribute: 'str') -> 't.Any'
Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named :file:`_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this::
hello = get_template_attribute('_cider.html', 'hello')
return hello('World')
.. versionadded:: 0.2
:param template_name: the name of the template
:param attribute: the name of the variable of macro to access
make_response(*args: 't.Any') -> 'Response'
Sometimes it is necessary to set additional headers in a view. Because
views do not have to return response objects but can return a value that
is converted into a response object by Flask itself, it becomes tricky to
add headers to it. This function can be called instead of using a return
and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header::
def index():
return render_template('index.html', foo=42)
You can now do something like this::
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
This function accepts the very same arguments you can return from a
view function. This for example creates a response with a 404 error
code::
response = make_response(render_template('not_found.html'), 404)
The other use case of this function is to force the return value of a
view function into a response which is helpful with view
decorators::
response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'
Internally this function does the following things:
- if no arguments are passed, it creates a new response argument
- if one argument is passed, :meth:`flask.Flask.make_response`
is invoked with it.
- if more than one argument is passed, the arguments are passed
to the :meth:`flask.Flask.make_response` function as tuple.
.. versionadded:: 0.6
redirect(location: 'str', code: 'int' = 302, Response: 'type[BaseResponse] | None' = None) -> 'BaseResponse'
Create a redirect response object.
If :data:`~flask.current_app` is available, it will use its
:meth:`~flask.Flask.redirect` method, otherwise it will use
:func:`werkzeug.utils.redirect`.
:param location: The URL to redirect to.
:param code: The status code for the redirect.
:param Response: The response class to use. Not used when
``current_app`` is active, which uses ``app.response_class``.
.. versionadded:: 2.2
Calls ``current_app.redirect`` if available instead of always
using Werkzeug's default ``redirect``.
send_file(path_or_file: 'os.PathLike[t.AnyStr] | str | t.IO[bytes]', mimetype: 'str | None' = None, as_attachment: 'bool' = False, download_name: 'str | None' = None, conditional: 'bool' = True, etag: 'bool | str' = True, last_modified: 'datetime | int | float | None' = None, max_age: 'None | (int | t.Callable[[str | None], int | None])' = None) -> 'Response'
Send the contents of a file to the client.
The first argument can be a file path or a file-like object. Paths
are preferred in most cases because Werkzeug can manage the file and
get extra information from the path. Passing a file-like object
requires that the file is opened in binary mode, and is mostly
useful when building a file in memory with :class:`io.BytesIO`.
Never pass file paths provided by a user. The path is assumed to be
trusted, so a user could craft a path to access a file you didn't
intend. Use :func:`send_from_directory` to safely serve
user-requested paths from within a directory.
If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
if the HTTP server supports ``X-Sendfile``, configuring Flask with
``USE_X_SENDFILE = True`` will tell the server to send the given
path, which is much more efficient than reading it in Python.
:param path_or_file: The path to the file to send, relative to the
current working directory if a relative path is given.
Alternatively, a file-like object opened in binary mode. Make
sure the file pointer is seeked to the start of the data.
:param mimetype: The MIME type to send for the file. If not
provided, it will try to detect it from the file name.
:param as_attachment: Indicate to a browser that it should offer to
save the file instead of displaying it.
:param download_name: The default name browsers will use when saving
the file. Defaults to the passed file name.
:param conditional: Enable conditional and range responses based on
request headers. Requires passing a file path and ``environ``.
:param etag: Calculate an ETag for the file, which requires passing
a file path. Can also be a string to use instead.
:param last_modified: The last modified time to send for the file,
in seconds. If not provided, it will try to detect it from the
file path.
:param max_age: How long the client should cache the file, in
seconds. If set, ``Cache-Control`` will be ``public``, otherwise
it will be ``no-cache`` to prefer conditional caching.
.. versionchanged:: 2.0
``download_name`` replaces the ``attachment_filename``
parameter. If ``as_attachment=False``, it is passed with
``Content-Disposition: inline`` instead.
.. versionchanged:: 2.0
``max_age`` replaces the ``cache_timeout`` parameter.
``conditional`` is enabled and ``max_age`` is not set by
default.
.. versionchanged:: 2.0
``etag`` replaces the ``add_etags`` parameter. It can be a
string to use instead of generating one.
.. versionchanged:: 2.0
Passing a file-like object that inherits from
:class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
than sending an empty file.
.. versionadded:: 2.0
Moved the implementation to Werkzeug. This is now a wrapper to
pass some Flask-specific arguments.
.. versionchanged:: 1.1
``filename`` may be a :class:`~os.PathLike` object.
.. versionchanged:: 1.1
Passing a :class:`~io.BytesIO` object supports range requests.
.. versionchanged:: 1.0.3
Filenames are encoded with ASCII instead of Latin-1 for broader
compatibility with WSGI servers.
.. versionchanged:: 1.0
UTF-8 filenames as specified in :rfc:`2231` are supported.
.. versionchanged:: 0.12
The filename is no longer automatically inferred from file
objects. If you want to use automatic MIME and etag support,
pass a filename via ``filename_or_fp`` or
``attachment_filename``.
.. versionchanged:: 0.12
``attachment_filename`` is preferred over ``filename`` for MIME
detection.
.. versionchanged:: 0.9
``cache_timeout`` defaults to
:meth:`Flask.get_send_file_max_age`.
.. versionchanged:: 0.7
MIME guessing and etag support for file-like objects was
removed because it was unreliable. Pass a filename if you are
able to, otherwise attach an etag yourself.
.. versionchanged:: 0.5
The ``add_etags``, ``cache_timeout`` and ``conditional``
parameters were added. The default behavior is to add etags.
.. versionadded:: 0.2
send_from_directory(directory: 'os.PathLike[str] | str', path: 'os.PathLike[str] | str', **kwargs: 't.Any') -> 'Response'
Send a file from within a directory using :func:`send_file`.
.. code-block:: python
@app.route("/uploads/<path:name>")
def download_file(name):
return send_from_directory(
app.config['UPLOAD_FOLDER'], name, as_attachment=True
)
This is a secure way to serve files from a folder, such as static
files or uploads. Uses :func:`~werkzeug.security.safe_join` to
ensure the path coming from the client is not maliciously crafted to
point outside the specified directory.
If the final path does not point to an existing regular file,
raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
:param directory: The directory that ``path`` must be located under,
relative to the current application's root path. This *must not*
be a value provided by the client, otherwise it becomes insecure.
:param path: The path to the file to send, relative to
``directory``.
:param kwargs: Arguments to pass to :func:`send_file`.
.. versionchanged:: 2.0
``path`` replaces the ``filename`` parameter.
.. versionadded:: 2.0
Moved the implementation to Werkzeug. This is now a wrapper to
pass some Flask-specific arguments.
.. versionadded:: 0.5
stream_with_context(generator_or_function: 't.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]]') -> 't.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]'
Wrap a response generator function so that it runs inside the current
request context. This keeps :data:`request`, :data:`session`, and :data:`g`
available, even though at the point the generator runs the request context
will typically have ended.
Use it as a decorator on a generator function:
.. code-block:: python
from flask import stream_with_context, request, Response
@app.get("/stream")
def streamed_response():
@stream_with_context
def generate():
yield "Hello "
yield request.args["name"]
yield "!"
return Response(generate())
Or use it as a wrapper around a created generator:
.. code-block:: python
from flask import stream_with_context, request, Response
@app.get("/stream")
def streamed_response():
def generate():
yield "Hello "
yield request.args["name"]
yield "!"
return Response(stream_with_context(generate()))
.. versionadded:: 0.9
url_for(endpoint: 'str', *, _anchor: 'str | None' = None, _method: 'str | None' = None, _scheme: 'str | None' = None, _external: 'bool | None' = None, **values: 't.Any') -> 'str'
Generate a URL to the given endpoint with the given values.
This requires an active request or application context, and calls
:meth:`current_app.url_for() <flask.Flask.url_for>`. See that method
for full documentation.
:param endpoint: The endpoint name associated with the URL to
generate. If this starts with a ``.``, the current blueprint
name (if any) will be used.
:param _anchor: If given, append this as ``#anchor`` to the URL.
:param _method: If given, generate the URL associated with this
method for the endpoint.
:param _scheme: If given, the URL will have this scheme if it is
external.
:param _external: If given, prefer the URL to be internal (False) or
require it to be external (True). External URLs include the
scheme and domain. When not in an active request, URLs are
external by default.
:param values: Values to use for the variable parts of the URL rule.
Unknown keys are appended as query string arguments, like
``?a=b&c=d``.
.. versionchanged:: 2.2
Calls ``current_app.url_for``, allowing an app to override the
behavior.
.. versionchanged:: 0.10
The ``_scheme`` parameter was added.
.. versionchanged:: 0.9
The ``_anchor`` and ``_method`` parameters were added.
.. versionchanged:: 0.9
Calls ``app.handle_url_build_error`` on build errors.
DATA
current_app = <LocalProxy unbound>
message_flashed = <blinker.base.NamedSignal object at 0x0000023208494B...
request = <LocalProxy unbound>
request_ctx = <LocalProxy unbound>
session = <LocalProxy unbound>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\helpers.py
flask.json
Python Library Documentation: package flask.json in flask
NAME
flask.json
PACKAGE CONTENTS
provider
tag
FUNCTIONS
dump(obj: 't.Any', fp: 't.IO[str]', **kwargs: 't.Any') -> 'None'
Serialize data as JSON and write to a file.
If :data:`~flask.current_app` is available, it will use its
:meth:`app.json.dump() <flask.json.provider.JSONProvider.dump>`
method, otherwise it will use :func:`json.dump`.
:param obj: The data to serialize.
:param fp: A file opened for writing text. Should use the UTF-8
encoding to be valid JSON.
:param kwargs: Arguments passed to the ``dump`` implementation.
.. versionchanged:: 2.3
The ``app`` parameter was removed.
.. versionchanged:: 2.2
Calls ``current_app.json.dump``, allowing an app to override
the behavior.
.. versionchanged:: 2.0
Writing to a binary file, and the ``encoding`` argument, will be
removed in Flask 2.1.
dumps(obj: 't.Any', **kwargs: 't.Any') -> 'str'
Serialize data as JSON.
If :data:`~flask.current_app` is available, it will use its
:meth:`app.json.dumps() <flask.json.provider.JSONProvider.dumps>`
method, otherwise it will use :func:`json.dumps`.
:param obj: The data to serialize.
:param kwargs: Arguments passed to the ``dumps`` implementation.
.. versionchanged:: 2.3
The ``app`` parameter was removed.
.. versionchanged:: 2.2
Calls ``current_app.json.dumps``, allowing an app to override
the behavior.
.. versionchanged:: 2.0.2
:class:`decimal.Decimal` is supported by converting to a string.
.. versionchanged:: 2.0
``encoding`` will be removed in Flask 2.1.
.. versionchanged:: 1.0.3
``app`` can be passed directly, rather than requiring an app
context for configuration.
jsonify(*args: 't.Any', **kwargs: 't.Any') -> 'Response'
Serialize the given arguments as JSON, and return a
:class:`~flask.Response` object with the ``application/json``
mimetype. A dict or list returned from a view will be converted to a
JSON response automatically without needing to call this.
This requires an active request or application context, and calls
:meth:`app.json.response() <flask.json.provider.JSONProvider.response>`.
In debug mode, the output is formatted with indentation to make it
easier to read. This may also be controlled by the provider.
Either positional or keyword arguments can be given, not both.
If no arguments are given, ``None`` is serialized.
:param args: A single value to serialize, or multiple values to
treat as a list to serialize.
:param kwargs: Treat as a dict to serialize.
.. versionchanged:: 2.2
Calls ``current_app.json.response``, allowing an app to override
the behavior.
.. versionchanged:: 2.0.2
:class:`decimal.Decimal` is supported by converting to a string.
.. versionchanged:: 0.11
Added support for serializing top-level arrays. This was a
security risk in ancient browsers. See :ref:`security-json`.
.. versionadded:: 0.2
load(fp: 't.IO[t.AnyStr]', **kwargs: 't.Any') -> 't.Any'
Deserialize data as JSON read from a file.
If :data:`~flask.current_app` is available, it will use its
:meth:`app.json.load() <flask.json.provider.JSONProvider.load>`
method, otherwise it will use :func:`json.load`.
:param fp: A file opened for reading text or UTF-8 bytes.
:param kwargs: Arguments passed to the ``load`` implementation.
.. versionchanged:: 2.3
The ``app`` parameter was removed.
.. versionchanged:: 2.2
Calls ``current_app.json.load``, allowing an app to override
the behavior.
.. versionchanged:: 2.2
The ``app`` parameter will be removed in Flask 2.3.
.. versionchanged:: 2.0
``encoding`` will be removed in Flask 2.1. The file must be text
mode, or binary mode with UTF-8 bytes.
loads(s: 'str | bytes', **kwargs: 't.Any') -> 't.Any'
Deserialize data as JSON.
If :data:`~flask.current_app` is available, it will use its
:meth:`app.json.loads() <flask.json.provider.JSONProvider.loads>`
method, otherwise it will use :func:`json.loads`.
:param s: Text or UTF-8 bytes.
:param kwargs: Arguments passed to the ``loads`` implementation.
.. versionchanged:: 2.3
The ``app`` parameter was removed.
.. versionchanged:: 2.2
Calls ``current_app.json.loads``, allowing an app to override
the behavior.
.. versionchanged:: 2.0
``encoding`` will be removed in Flask 2.1. The data must be a
string or UTF-8 bytes.
.. versionchanged:: 1.0.3
``app`` can be passed directly, rather than requiring an app
context for configuration.
DATA
current_app = <LocalProxy unbound>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\json\__init__.py
flask.jsonify
Python Library Documentation: function jsonify in module flask.json
jsonify(*args: 't.Any', **kwargs: 't.Any') -> 'Response'
Serialize the given arguments as JSON, and return a
:class:`~flask.Response` object with the ``application/json``
mimetype. A dict or list returned from a view will be converted to a
JSON response automatically without needing to call this.
This requires an active request or application context, and calls
:meth:`app.json.response() <flask.json.provider.JSONProvider.response>`.
In debug mode, the output is formatted with indentation to make it
easier to read. This may also be controlled by the provider.
Either positional or keyword arguments can be given, not both.
If no arguments are given, ``None`` is serialized.
:param args: A single value to serialize, or multiple values to
treat as a list to serialize.
:param kwargs: Treat as a dict to serialize.
.. versionchanged:: 2.2
Calls ``current_app.json.response``, allowing an app to override
the behavior.
.. versionchanged:: 2.0.2
:class:`decimal.Decimal` is supported by converting to a string.
.. versionchanged:: 0.11
Added support for serializing top-level arrays. This was a
security risk in ancient browsers. See :ref:`security-json`.
.. versionadded:: 0.2
flask.logging
Python Library Documentation: module flask.logging in flask
NAME
flask.logging
FUNCTIONS
create_logger(app: 'App') -> 'logging.Logger'
Get the Flask app's logger and configure it if needed.
The logger name will be the same as
:attr:`app.import_name <flask.Flask.name>`.
When :attr:`~flask.Flask.debug` is enabled, set the logger level to
:data:`logging.DEBUG` if it is not set.
If there is no handler for the logger's effective level, add a
:class:`~logging.StreamHandler` for
:func:`~flask.logging.wsgi_errors_stream` with a basic format.
has_level_handler(logger: 'logging.Logger') -> 'bool'
Check if there is a handler in the logging chain that will handle the
given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.
DATA
default_handler = <StreamHandler <stderr> (NOTSET)>
request = <LocalProxy unbound>
wsgi_errors_stream = <_io.TextIOWrapper name='<stderr>' mode='w' encod...
Character and line based layer over a BufferedIOBase object, buffer.
encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getencoding().
errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict".
newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.
If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\logging.py
flask.make_response
Python Library Documentation: function make_response in module flask.helpers
make_response(*args: 't.Any') -> 'Response'
Sometimes it is necessary to set additional headers in a view. Because
views do not have to return response objects but can return a value that
is converted into a response object by Flask itself, it becomes tricky to
add headers to it. This function can be called instead of using a return
and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header::
def index():
return render_template('index.html', foo=42)
You can now do something like this::
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
This function accepts the very same arguments you can return from a
view function. This for example creates a response with a 404 error
code::
response = make_response(render_template('not_found.html'), 404)
The other use case of this function is to force the return value of a
view function into a response which is helpful with view
decorators::
response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'
Internally this function does the following things:
- if no arguments are passed, it creates a new response argument
- if one argument is passed, :meth:`flask.Flask.make_response`
is invoked with it.
- if more than one argument is passed, the arguments are passed
to the :meth:`flask.Flask.make_response` function as tuple.
.. versionadded:: 0.6
flask.message_flashed
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.redirect
Python Library Documentation: function redirect in module flask.helpers
redirect(location: 'str', code: 'int' = 302, Response: 'type[BaseResponse] | None' = None) -> 'BaseResponse'
Create a redirect response object.
If :data:`~flask.current_app` is available, it will use its
:meth:`~flask.Flask.redirect` method, otherwise it will use
:func:`werkzeug.utils.redirect`.
:param location: The URL to redirect to.
:param code: The status code for the redirect.
:param Response: The response class to use. Not used when
``current_app`` is active, which uses ``app.response_class``.
.. versionadded:: 2.2
Calls ``current_app.redirect`` if available instead of always
using Werkzeug's default ``redirect``.
flask.render_template
Python Library Documentation: function render_template in module flask.templating
render_template(template_name_or_list: 'str | Template | list[str | Template]', **context: 't.Any') -> 'str'
Render a template by name with the given context.
:param template_name_or_list: The name of the template to render. If
a list is given, the first name to exist will be rendered.
:param context: The variables to make available in the template.
flask.render_template_string
Python Library Documentation: function render_template_string in module flask.templating
render_template_string(source: 'str', **context: 't.Any') -> 'str'
Render a template from the given source string with the given
context.
:param source: The source code of the template to render.
:param context: The variables to make available in the template.
flask.request
Error rendering doc: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
flask.request_finished
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.request_started
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.request_tearing_down
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.sansio
Python Library Documentation: package flask.sansio in flask
NAME
flask.sansio
PACKAGE CONTENTS
app
blueprints
scaffold
FILE
(built-in)
flask.send_file
Python Library Documentation: function send_file in module flask.helpers
send_file(path_or_file: 'os.PathLike[t.AnyStr] | str | t.IO[bytes]', mimetype: 'str | None' = None, as_attachment: 'bool' = False, download_name: 'str | None' = None, conditional: 'bool' = True, etag: 'bool | str' = True, last_modified: 'datetime | int | float | None' = None, max_age: 'None | (int | t.Callable[[str | None], int | None])' = None) -> 'Response'
Send the contents of a file to the client.
The first argument can be a file path or a file-like object. Paths
are preferred in most cases because Werkzeug can manage the file and
get extra information from the path. Passing a file-like object
requires that the file is opened in binary mode, and is mostly
useful when building a file in memory with :class:`io.BytesIO`.
Never pass file paths provided by a user. The path is assumed to be
trusted, so a user could craft a path to access a file you didn't
intend. Use :func:`send_from_directory` to safely serve
user-requested paths from within a directory.
If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
if the HTTP server supports ``X-Sendfile``, configuring Flask with
``USE_X_SENDFILE = True`` will tell the server to send the given
path, which is much more efficient than reading it in Python.
:param path_or_file: The path to the file to send, relative to the
current working directory if a relative path is given.
Alternatively, a file-like object opened in binary mode. Make
sure the file pointer is seeked to the start of the data.
:param mimetype: The MIME type to send for the file. If not
provided, it will try to detect it from the file name.
:param as_attachment: Indicate to a browser that it should offer to
save the file instead of displaying it.
:param download_name: The default name browsers will use when saving
the file. Defaults to the passed file name.
:param conditional: Enable conditional and range responses based on
request headers. Requires passing a file path and ``environ``.
:param etag: Calculate an ETag for the file, which requires passing
a file path. Can also be a string to use instead.
:param last_modified: The last modified time to send for the file,
in seconds. If not provided, it will try to detect it from the
file path.
:param max_age: How long the client should cache the file, in
seconds. If set, ``Cache-Control`` will be ``public``, otherwise
it will be ``no-cache`` to prefer conditional caching.
.. versionchanged:: 2.0
``download_name`` replaces the ``attachment_filename``
parameter. If ``as_attachment=False``, it is passed with
``Content-Disposition: inline`` instead.
.. versionchanged:: 2.0
``max_age`` replaces the ``cache_timeout`` parameter.
``conditional`` is enabled and ``max_age`` is not set by
default.
.. versionchanged:: 2.0
``etag`` replaces the ``add_etags`` parameter. It can be a
string to use instead of generating one.
.. versionchanged:: 2.0
Passing a file-like object that inherits from
:class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
than sending an empty file.
.. versionadded:: 2.0
Moved the implementation to Werkzeug. This is now a wrapper to
pass some Flask-specific arguments.
.. versionchanged:: 1.1
``filename`` may be a :class:`~os.PathLike` object.
.. versionchanged:: 1.1
Passing a :class:`~io.BytesIO` object supports range requests.
.. versionchanged:: 1.0.3
Filenames are encoded with ASCII instead of Latin-1 for broader
compatibility with WSGI servers.
.. versionchanged:: 1.0
UTF-8 filenames as specified in :rfc:`2231` are supported.
.. versionchanged:: 0.12
The filename is no longer automatically inferred from file
objects. If you want to use automatic MIME and etag support,
pass a filename via ``filename_or_fp`` or
``attachment_filename``.
.. versionchanged:: 0.12
``attachment_filename`` is preferred over ``filename`` for MIME
detection.
.. versionchanged:: 0.9
``cache_timeout`` defaults to
:meth:`Flask.get_send_file_max_age`.
.. versionchanged:: 0.7
MIME guessing and etag support for file-like objects was
removed because it was unreliable. Pass a filename if you are
able to, otherwise attach an etag yourself.
.. versionchanged:: 0.5
The ``add_etags``, ``cache_timeout`` and ``conditional``
parameters were added. The default behavior is to add etags.
.. versionadded:: 0.2
flask.send_from_directory
Python Library Documentation: function send_from_directory in module flask.helpers
send_from_directory(directory: 'os.PathLike[str] | str', path: 'os.PathLike[str] | str', **kwargs: 't.Any') -> 'Response'
Send a file from within a directory using :func:`send_file`.
.. code-block:: python
@app.route("/uploads/<path:name>")
def download_file(name):
return send_from_directory(
app.config['UPLOAD_FOLDER'], name, as_attachment=True
)
This is a secure way to serve files from a folder, such as static
files or uploads. Uses :func:`~werkzeug.security.safe_join` to
ensure the path coming from the client is not maliciously crafted to
point outside the specified directory.
If the final path does not point to an existing regular file,
raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
:param directory: The directory that ``path`` must be located under,
relative to the current application's root path. This *must not*
be a value provided by the client, otherwise it becomes insecure.
:param path: The path to the file to send, relative to
``directory``.
:param kwargs: Arguments to pass to :func:`send_file`.
.. versionchanged:: 2.0
``path`` replaces the ``filename`` parameter.
.. versionadded:: 2.0
Moved the implementation to Werkzeug. This is now a wrapper to
pass some Flask-specific arguments.
.. versionadded:: 0.5
flask.session
Error rendering doc: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
flask.sessions
Python Library Documentation: module flask.sessions in flask
NAME
flask.sessions
CLASSES
builtins.object
SessionInterface
SecureCookieSessionInterface
collections.abc.MutableMapping(collections.abc.Mapping)
SessionMixin
SecureCookieSession(werkzeug.datastructures.structures.CallbackDict, SessionMixin)
NullSession
werkzeug.datastructures.structures.CallbackDict(werkzeug.datastructures.mixins.UpdateDictMixin, builtins.dict)
SecureCookieSession(werkzeug.datastructures.structures.CallbackDict, SessionMixin)
NullSession
class NullSession(SecureCookieSession)
| NullSession(initial: 'c.Mapping[str, t.Any] | None' = None) -> 'None'
|
| Class used to generate nicer error messages if sessions are not
| available. Will still allow read-only access to the empty session
| but fail on setting.
|
| Method resolution order:
| NullSession
| SecureCookieSession
| werkzeug.datastructures.structures.CallbackDict
| werkzeug.datastructures.mixins.UpdateDictMixin
| builtins.dict
| SessionMixin
| collections.abc.MutableMapping
| collections.abc.Mapping
| collections.abc.Collection
| collections.abc.Sized
| collections.abc.Iterable
| collections.abc.Container
| builtins.object
|
| Methods defined here:
|
| __delitem__ = _fail(self, *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
|
| __setitem__ = _fail(self, *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
|
| clear = _fail(self, *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
|
| pop = _fail(self, *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
|
| popitem = _fail(self, *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
|
| setdefault = _fail(self, *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
|
| update = _fail(self, *args: 't.Any', **kwargs: 't.Any') -> 't.NoReturn'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from SecureCookieSession:
|
| __init__(self, initial: 'c.Mapping[str, t.Any] | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from SecureCookieSession:
|
| __orig_bases__ = (werkzeug.datastructures.structures.CallbackDict[str,...
|
| modified = False
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.datastructures.structures.CallbackDict:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.datastructures.mixins.UpdateDictMixin:
|
| __ior__(self, other: 'cabc.Mapping[K, V] | cabc.Iterable[tuple[K, V]]') -> 'te.Self'
| Return self|=value.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.datastructures.mixins.UpdateDictMixin:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.datastructures.mixins.UpdateDictMixin:
|
| on_update = None
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from builtins.dict:
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Data descriptors inherited from SessionMixin:
|
| permanent
| This reflects the ``'_permanent'`` key in the dict.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from SessionMixin:
|
| accessed = False
|
| new = False
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
class SecureCookieSession(werkzeug.datastructures.structures.CallbackDict, SessionMixin)
| SecureCookieSession(initial: 'c.Mapping[str, t.Any] | None' = None) -> 'None'
|
| Base class for sessions based on signed cookies.
|
| This session backend will set the :attr:`modified` and
| :attr:`accessed` attributes. It cannot reliably track whether a
| session is new (vs. empty), so :attr:`new` remains hard coded to
| ``False``.
|
| Method resolution order:
| SecureCookieSession
| werkzeug.datastructures.structures.CallbackDict
| werkzeug.datastructures.mixins.UpdateDictMixin
| builtins.dict
| SessionMixin
| collections.abc.MutableMapping
| collections.abc.Mapping
| collections.abc.Collection
| collections.abc.Sized
| collections.abc.Iterable
| collections.abc.Container
| builtins.object
|
| Methods defined here:
|
| __init__(self, initial: 'c.Mapping[str, t.Any] | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __orig_bases__ = (werkzeug.datastructures.structures.CallbackDict[str,...
|
| modified = False
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.datastructures.structures.CallbackDict:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.datastructures.mixins.UpdateDictMixin:
|
| __delitem__(self, key: 'K') -> 'None'
| Delete self[key].
|
| __ior__(self, other: 'cabc.Mapping[K, V] | cabc.Iterable[tuple[K, V]]') -> 'te.Self'
| Return self|=value.
|
| __setitem__(self, key: 'K', value: 'V') -> 'None'
| Set self[key] to value.
|
| clear(self) -> 'None'
| D.clear() -> None. Remove all items from D.
|
| pop(self: 'te.Self', key: 'K', default: 'V | T' = no value) -> 'V | T'
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self) -> 'tuple[K, V]'
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self: 'te.Self', key: 'K', default: 'V | None' = None) -> 'V'
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(self, arg: 'cabc.Mapping[K, V] | cabc.Iterable[tuple[K, V]] | None' = None, /, **kwargs: 'V') -> 'None'
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.datastructures.mixins.UpdateDictMixin:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.datastructures.mixins.UpdateDictMixin:
|
| on_update = None
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from builtins.dict:
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Data descriptors inherited from SessionMixin:
|
| permanent
| This reflects the ``'_permanent'`` key in the dict.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from SessionMixin:
|
| accessed = False
|
| new = False
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
class SecureCookieSessionInterface(SessionInterface)
| The default session interface that stores sessions in signed cookies
| through the :mod:`itsdangerous` module.
|
| Method resolution order:
| SecureCookieSessionInterface
| SessionInterface
| builtins.object
|
| Methods defined here:
|
| get_signing_serializer(self, app: 'Flask') -> 'URLSafeTimedSerializer | None'
|
| open_session(self, app: 'Flask', request: 'Request') -> 'SecureCookieSession | None'
| This is called at the beginning of each request, after
| pushing the request context, before matching the URL.
|
| This must return an object which implements a dictionary-like
| interface as well as the :class:`SessionMixin` interface.
|
| This will return ``None`` to indicate that loading failed in
| some way that is not immediately an error. The request
| context will fall back to using :meth:`make_null_session`
| in this case.
|
| save_session(self, app: 'Flask', session: 'SessionMixin', response: 'Response') -> 'None'
| This is called at the end of each request, after generating
| a response, before removing the request context. It is skipped
| if :meth:`is_null_session` returns ``True``.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| digest_method = _lazy_sha1(string: 'bytes' = b'') -> 't.Any'
| Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
| SHA-1, in which case the import and use as a default would fail before the
| developer can configure something else.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| key_derivation = 'hmac'
|
| salt = 'cookie-session'
|
| serializer = <flask.json.tag.TaggedJSONSerializer object>
|
| session_class = <class 'flask.sessions.SecureCookieSession'>
| Base class for sessions based on signed cookies.
|
| This session backend will set the :attr:`modified` and
| :attr:`accessed` attributes. It cannot reliably track whether a
| session is new (vs. empty), so :attr:`new` remains hard coded to
| ``False``.
|
|
| ----------------------------------------------------------------------
| Methods inherited from SessionInterface:
|
| get_cookie_domain(self, app: 'Flask') -> 'str | None'
| The value of the ``Domain`` parameter on the session cookie. If not set,
| browsers will only send the cookie to the exact domain it was set from.
| Otherwise, they will send it to any subdomain of the given value as well.
|
| Uses the :data:`SESSION_COOKIE_DOMAIN` config.
|
| .. versionchanged:: 2.3
| Not set by default, does not fall back to ``SERVER_NAME``.
|
| get_cookie_httponly(self, app: 'Flask') -> 'bool'
| Returns True if the session cookie should be httponly. This
| currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``
| config var.
|
| get_cookie_name(self, app: 'Flask') -> 'str'
| The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``.
|
| get_cookie_partitioned(self, app: 'Flask') -> 'bool'
| Returns True if the cookie should be partitioned. By default, uses
| the value of :data:`SESSION_COOKIE_PARTITIONED`.
|
| .. versionadded:: 3.1
|
| get_cookie_path(self, app: 'Flask') -> 'str'
| Returns the path for which the cookie should be valid. The
| default implementation uses the value from the ``SESSION_COOKIE_PATH``
| config var if it's set, and falls back to ``APPLICATION_ROOT`` or
| uses ``/`` if it's ``None``.
|
| get_cookie_samesite(self, app: 'Flask') -> 'str | None'
| Return ``'Strict'`` or ``'Lax'`` if the cookie should use the
| ``SameSite`` attribute. This currently just returns the value of
| the :data:`SESSION_COOKIE_SAMESITE` setting.
|
| get_cookie_secure(self, app: 'Flask') -> 'bool'
| Returns True if the cookie should be secure. This currently
| just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
|
| get_expiration_time(self, app: 'Flask', session: 'SessionMixin') -> 'datetime | None'
| A helper method that returns an expiration date for the session
| or ``None`` if the session is linked to the browser session. The
| default implementation returns now + the permanent session
| lifetime configured on the application.
|
| is_null_session(self, obj: 'object') -> 'bool'
| Checks if a given object is a null session. Null sessions are
| not asked to be saved.
|
| This checks if the object is an instance of :attr:`null_session_class`
| by default.
|
| make_null_session(self, app: 'Flask') -> 'NullSession'
| Creates a null session which acts as a replacement object if the
| real session support could not be loaded due to a configuration
| error. This mainly aids the user experience because the job of the
| null session is to still support lookup without complaining but
| modifications are answered with a helpful error message of what
| failed.
|
| This creates an instance of :attr:`null_session_class` by default.
|
| should_set_cookie(self, app: 'Flask', session: 'SessionMixin') -> 'bool'
| Used by session backends to determine if a ``Set-Cookie`` header
| should be set for this session cookie for this response. If the session
| has been modified, the cookie is set. If the session is permanent and
| the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is
| always set.
|
| This check is usually skipped if the session was deleted.
|
| .. versionadded:: 0.11
|
| ----------------------------------------------------------------------
| Data descriptors inherited from SessionInterface:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from SessionInterface:
|
| null_session_class = <class 'flask.sessions.NullSession'>
| Class used to generate nicer error messages if sessions are not
| available. Will still allow read-only access to the empty session
| but fail on setting.
|
|
| pickle_based = False
class SessionInterface(builtins.object)
| The basic interface you have to implement in order to replace the
| default session interface which uses werkzeug's securecookie
| implementation. The only methods you have to implement are
| :meth:`open_session` and :meth:`save_session`, the others have
| useful defaults which you don't need to change.
|
| The session object returned by the :meth:`open_session` method has to
| provide a dictionary like interface plus the properties and methods
| from the :class:`SessionMixin`. We recommend just subclassing a dict
| and adding that mixin::
|
| class Session(dict, SessionMixin):
| pass
|
| If :meth:`open_session` returns ``None`` Flask will call into
| :meth:`make_null_session` to create a session that acts as replacement
| if the session support cannot work because some requirement is not
| fulfilled. The default :class:`NullSession` class that is created
| will complain that the secret key was not set.
|
| To replace the session interface on an application all you have to do
| is to assign :attr:`flask.Flask.session_interface`::
|
| app = Flask(__name__)
| app.session_interface = MySessionInterface()
|
| Multiple requests with the same session may be sent and handled
| concurrently. When implementing a new session interface, consider
| whether reads or writes to the backing store must be synchronized.
| There is no guarantee on the order in which the session for each
| request is opened or saved, it will occur in the order that requests
| begin and end processing.
|
| .. versionadded:: 0.8
|
| Methods defined here:
|
| get_cookie_domain(self, app: 'Flask') -> 'str | None'
| The value of the ``Domain`` parameter on the session cookie. If not set,
| browsers will only send the cookie to the exact domain it was set from.
| Otherwise, they will send it to any subdomain of the given value as well.
|
| Uses the :data:`SESSION_COOKIE_DOMAIN` config.
|
| .. versionchanged:: 2.3
| Not set by default, does not fall back to ``SERVER_NAME``.
|
| get_cookie_httponly(self, app: 'Flask') -> 'bool'
| Returns True if the session cookie should be httponly. This
| currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``
| config var.
|
| get_cookie_name(self, app: 'Flask') -> 'str'
| The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``.
|
| get_cookie_partitioned(self, app: 'Flask') -> 'bool'
| Returns True if the cookie should be partitioned. By default, uses
| the value of :data:`SESSION_COOKIE_PARTITIONED`.
|
| .. versionadded:: 3.1
|
| get_cookie_path(self, app: 'Flask') -> 'str'
| Returns the path for which the cookie should be valid. The
| default implementation uses the value from the ``SESSION_COOKIE_PATH``
| config var if it's set, and falls back to ``APPLICATION_ROOT`` or
| uses ``/`` if it's ``None``.
|
| get_cookie_samesite(self, app: 'Flask') -> 'str | None'
| Return ``'Strict'`` or ``'Lax'`` if the cookie should use the
| ``SameSite`` attribute. This currently just returns the value of
| the :data:`SESSION_COOKIE_SAMESITE` setting.
|
| get_cookie_secure(self, app: 'Flask') -> 'bool'
| Returns True if the cookie should be secure. This currently
| just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
|
| get_expiration_time(self, app: 'Flask', session: 'SessionMixin') -> 'datetime | None'
| A helper method that returns an expiration date for the session
| or ``None`` if the session is linked to the browser session. The
| default implementation returns now + the permanent session
| lifetime configured on the application.
|
| is_null_session(self, obj: 'object') -> 'bool'
| Checks if a given object is a null session. Null sessions are
| not asked to be saved.
|
| This checks if the object is an instance of :attr:`null_session_class`
| by default.
|
| make_null_session(self, app: 'Flask') -> 'NullSession'
| Creates a null session which acts as a replacement object if the
| real session support could not be loaded due to a configuration
| error. This mainly aids the user experience because the job of the
| null session is to still support lookup without complaining but
| modifications are answered with a helpful error message of what
| failed.
|
| This creates an instance of :attr:`null_session_class` by default.
|
| open_session(self, app: 'Flask', request: 'Request') -> 'SessionMixin | None'
| This is called at the beginning of each request, after
| pushing the request context, before matching the URL.
|
| This must return an object which implements a dictionary-like
| interface as well as the :class:`SessionMixin` interface.
|
| This will return ``None`` to indicate that loading failed in
| some way that is not immediately an error. The request
| context will fall back to using :meth:`make_null_session`
| in this case.
|
| save_session(self, app: 'Flask', session: 'SessionMixin', response: 'Response') -> 'None'
| This is called at the end of each request, after generating
| a response, before removing the request context. It is skipped
| if :meth:`is_null_session` returns ``True``.
|
| should_set_cookie(self, app: 'Flask', session: 'SessionMixin') -> 'bool'
| Used by session backends to determine if a ``Set-Cookie`` header
| should be set for this session cookie for this response. If the session
| has been modified, the cookie is set. If the session is permanent and
| the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is
| always set.
|
| This check is usually skipped if the session was deleted.
|
| .. versionadded:: 0.11
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| null_session_class = <class 'flask.sessions.NullSession'>
| Class used to generate nicer error messages if sessions are not
| available. Will still allow read-only access to the empty session
| but fail on setting.
|
|
| pickle_based = False
class SessionMixin(collections.abc.MutableMapping)
| Expands a basic dictionary with session attributes.
|
| Method resolution order:
| SessionMixin
| collections.abc.MutableMapping
| collections.abc.Mapping
| collections.abc.Collection
| collections.abc.Sized
| collections.abc.Iterable
| collections.abc.Container
| builtins.object
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| permanent
| This reflects the ``'_permanent'`` key in the dict.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__delitem__', '__getitem__', '__iter...
|
| __annotations__ = {}
|
| __orig_bases__ = (collections.abc.MutableMapping[str, typing.Any],)
|
| accessed = False
|
| modified = True
|
| new = False
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.MutableMapping:
|
| __delitem__(self, key)
|
| __setitem__(self, key, value)
|
| clear(self)
| D.clear() -> None. Remove all items from D.
|
| pop(self, key, default=<object object at 0x00000232059581F0>)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised.
|
| popitem(self)
| D.popitem() -> (k, v), remove and return some (key, value) pair
| as a 2-tuple; but raise KeyError if D is empty.
|
| setdefault(self, key, default=None)
| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
|
| update(self, other=(), /, **kwds)
| D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
| If E present and has a .keys() method, does: for k in E: D[k] = E[k]
| If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
| In either case, this is followed by: for k, v in F.items(): D[k] = v
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.Mapping:
|
| __contains__(self, key)
|
| __eq__(self, other)
| Return self==value.
|
| __getitem__(self, key)
|
| get(self, key, default=None)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(self)
| D.items() -> a set-like object providing a view on D's items
|
| keys(self)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(self)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from collections.abc.Mapping:
|
| __hash__ = None
|
| __reversed__ = None
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.Sized:
|
| __len__(self)
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.Iterable:
|
| __iter__(self)
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Iterable:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
DATA
session_json_serializer = <flask.json.tag.TaggedJSONSerializer object>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\sessions.py
flask.signals
Python Library Documentation: module flask.signals in flask
NAME
flask.signals
DATA
appcontext_popped = <blinker.base.NamedSignal object at 0x000002320849...
appcontext_pushed = <blinker.base.NamedSignal object at 0x000002320849...
appcontext_tearing_down = <blinker.base.NamedSignal object at 0x000002...
before_render_template = <blinker.base.NamedSignal object at 0x0000023...
got_request_exception = <blinker.base.NamedSignal object at 0x00000232...
message_flashed = <blinker.base.NamedSignal object at 0x0000023208494B...
request_finished = <blinker.base.NamedSignal object at 0x0000023208467...
request_started = <blinker.base.NamedSignal object at 0x00000232084673...
request_tearing_down = <blinker.base.NamedSignal object at 0x000002320...
template_rendered = <blinker.base.NamedSignal object at 0x000002320846...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\signals.py
flask.stream_template
Python Library Documentation: function stream_template in module flask.templating
stream_template(template_name_or_list: 'str | Template | list[str | Template]', **context: 't.Any') -> 't.Iterator[str]'
Render a template by name with the given context as a stream.
This returns an iterator of strings, which can be used as a
streaming response from a view.
:param template_name_or_list: The name of the template to render. If
a list is given, the first name to exist will be rendered.
:param context: The variables to make available in the template.
.. versionadded:: 2.2
flask.stream_template_string
Python Library Documentation: function stream_template_string in module flask.templating
stream_template_string(source: 'str', **context: 't.Any') -> 't.Iterator[str]'
Render a template from the given source string with the given
context as a stream. This returns an iterator of strings, which can
be used as a streaming response from a view.
:param source: The source code of the template to render.
:param context: The variables to make available in the template.
.. versionadded:: 2.2
flask.stream_with_context
Python Library Documentation: function stream_with_context in module flask.helpers
stream_with_context(generator_or_function: 't.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]]') -> 't.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]'
Wrap a response generator function so that it runs inside the current
request context. This keeps :data:`request`, :data:`session`, and :data:`g`
available, even though at the point the generator runs the request context
will typically have ended.
Use it as a decorator on a generator function:
.. code-block:: python
from flask import stream_with_context, request, Response
@app.get("/stream")
def streamed_response():
@stream_with_context
def generate():
yield "Hello "
yield request.args["name"]
yield "!"
return Response(generate())
Or use it as a wrapper around a created generator:
.. code-block:: python
from flask import stream_with_context, request, Response
@app.get("/stream")
def streamed_response():
def generate():
yield "Hello "
yield request.args["name"]
yield "!"
return Response(stream_with_context(generate()))
.. versionadded:: 0.9
flask.t
Python Library Documentation: module typing
NAME
typing - The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
MODULE REFERENCE
https://docs.python.org/3.12/library/typing.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
Among other things, the module includes the following:
* Generic, Protocol, and internal machinery to support generic aliases.
All subscripted types like X[int], Union[int, str] are generic aliases.
* Various "special forms" that have unique meanings in type annotations:
NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others.
* Classes whose instances can be type arguments to generic classes and functions:
TypeVar, ParamSpec, TypeVarTuple.
* Public helper functions: get_type_hints, overload, cast, final, and others.
* Several protocols to support duck-typing:
SupportsFloat, SupportsIndex, SupportsAbs, and others.
* Special types: NewType, NamedTuple, TypedDict.
* Deprecated wrapper submodules for re and io related types.
* Deprecated aliases for builtin types and collections.abc ABCs.
Any name not present in __all__ is an implementation detail
that may be changed without notice. Use at your own risk!
CLASSES
builtins.object
builtins.str
Annotated
Any
Generic
IO
BinaryIO
TextIO
Protocol
SupportsAbs
SupportsBytes
SupportsComplex
SupportsFloat
SupportsIndex
SupportsInt
SupportsRound
NewType
ParamSpec
ParamSpecArgs
ParamSpecKwargs
TypeAliasType
TypeVar
TypeVarTuple
_Final(builtins.object)
ForwardRef
class Annotated(builtins.object)
| Annotated(*args, **kwargs)
|
| Add context-specific metadata to a type.
|
| Example: Annotated[int, runtime_check.Unsigned] indicates to the
| hypothetical runtime_check module that this type is an unsigned int.
| Every other consumer of this type can ignore this metadata and treat
| this type as int.
|
| The first argument to Annotated must be a valid type.
|
| Details:
|
| - It's an error to call `Annotated` with less than two arguments.
| - Access the metadata via the ``__metadata__`` attribute::
|
| assert Annotated[int, '$'].__metadata__ == ('$',)
|
| - Nested Annotated types are flattened::
|
| assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
|
| - Instantiating an annotated type is equivalent to instantiating the
| underlying type::
|
| assert Annotated[C, Ann1](5) == C(5)
|
| - Annotated can be used as a generic type alias::
|
| type Optimized[T] = Annotated[T, runtime.Optimize()]
| # type checker will treat Optimized[int]
| # as equivalent to Annotated[int, runtime.Optimize()]
|
| type OptimizedList[T] = Annotated[list[T], runtime.Optimize()]
| # type checker will treat OptimizedList[int]
| # as equivalent to Annotated[list[int], runtime.Optimize()]
|
| - Annotated cannot be used with an unpacked TypeVarTuple::
|
| type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid
|
| This would be equivalent to::
|
| Annotated[T1, T2, T3, ..., Ann1]
|
| where T1, T2 etc. are TypeVars, which would be invalid, because
| only one type should be passed to Annotated.
|
| Class methods defined here:
|
| __class_getitem__(params)
|
| __init_subclass__(*args, **kwargs)
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, *args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
class Any(builtins.object)
| Any(*args, **kwargs)
|
| Special type indicating an unconstrained type.
|
| - Any is compatible with every type.
| - Any assumed to have all methods.
| - All values assumed to be instances of Any.
|
| Note that all the above statements are true from the point of view of
| static type checkers. At runtime, Any should not be used with instance
| checks.
|
| Static methods defined here:
|
| __new__(cls, *args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class BinaryIO(IO)
| Typed version of the return of open() in binary mode.
|
| Method resolution order:
| BinaryIO
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'BinaryIO'
|
| write(self, s: Union[bytes, bytearray]) -> int
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.IO[bytes],)
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from IO:
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties inherited from IO:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class ForwardRef(_Final)
| ForwardRef(arg, is_argument=True, module=None, *, is_class=False)
|
| Internal wrapper to hold a forward reference.
|
| Method resolution order:
| ForwardRef
| _Final
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, arg, is_argument=True, module=None, *, is_class=False)
| Initialize self. See help(type(self)) for accurate signature.
|
| __or__(self, other)
| Return self|value.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __forward_arg__
|
| __forward_code__
|
| __forward_evaluated__
|
| __forward_is_argument__
|
| __forward_is_class__
|
| __forward_module__
|
| __forward_value__
|
| ----------------------------------------------------------------------
| Class methods inherited from _Final:
|
| __init_subclass__(*args, **kwds)
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _Final:
|
| __weakref__
| list of weak references to the object
class Generic(builtins.object)
| Abstract base class for generic types.
|
| On Python 3.12 and newer, generic classes implicitly inherit from
| Generic when they declare a parameter list after the class's name::
|
| class Mapping[KT, VT]:
| def __getitem__(self, key: KT) -> VT:
| ...
| # Etc.
|
| On older versions of Python, however, generic classes have to
| explicitly inherit from Generic.
|
| After a class has been declared to be generic, it can then be used as
| follows::
|
| def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
| try:
| return mapping[key]
| except KeyError:
| return default
|
| Class methods defined here:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
class IO(Generic)
| Generic base class for TextIO and BinaryIO.
|
| This is an abstract, generic version of the return of open().
|
| NOTE: This does not distinguish between the different possible
| classes (text vs. binary, read vs. write vs. read/write,
| append-only, unbuffered). The TextIO and BinaryIO subclasses
| below capture the distinctions between text vs. binary, which is
| pervasive in the interface; however we currently do not offer a
| way to track the other distinctions in the type system.
|
| Method resolution order:
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'IO[AnyStr]'
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| write(self, s: ~AnyStr) -> int
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~AnyStr],)
|
| __parameters__ = (~AnyStr,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class NewType(builtins.object)
| NewType(name, tp)
|
| NewType creates simple unique types with almost zero runtime overhead.
|
| NewType(name, tp) is considered a subtype of tp
| by static type checkers. At runtime, NewType(name, tp) returns
| a dummy callable that simply returns its argument.
|
| Usage::
|
| UserId = NewType('UserId', int)
|
| def name_by_id(user_id: UserId) -> str:
| ...
|
| UserId('user') # Fails type check
|
| name_by_id(42) # Fails type check
| name_by_id(UserId(42)) # OK
|
| num = UserId(5) + 1 # type: int
|
| Methods defined here:
|
| __init__(self, name, tp)
| Initialize self. See help(type(self)) for accurate signature.
|
| __mro_entries__(self, bases)
|
| __or__(self, other)
| Return self|value.
|
| __reduce__(self)
| Helper for pickle.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __call__ = _idfunc(x, /)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ParamSpec(builtins.object)
| Parameter specification variable.
|
| The preferred way to construct a parameter specification is via the
| dedicated syntax for generic functions, classes, and type aliases,
| where the use of '**' creates a parameter specification::
|
| type IntFunc[**P] = Callable[P, int]
|
| For compatibility with Python 3.11 and earlier, ParamSpec objects
| can also be created as follows::
|
| P = ParamSpec('P')
|
| Parameter specification variables exist primarily for the benefit of
| static type checkers. They are used to forward the parameter types of
| one callable to another callable, a pattern commonly found in
| higher-order functions and decorators. They are only valid when used
| in ``Concatenate``, or as the first argument to ``Callable``, or as
| parameters for user-defined Generics. See class Generic for more
| information on generic types.
|
| An example for annotating a decorator::
|
| def add_logging[**P, T](f: Callable[P, T]) -> Callable[P, T]:
| '''A type-safe decorator to add logging to a function.'''
| def inner(*args: P.args, **kwargs: P.kwargs) -> T:
| logging.info(f'{f.__name__} was called')
| return f(*args, **kwargs)
| return inner
|
| @add_logging
| def add_two(x: float, y: float) -> float:
| '''Add two numbers together.'''
| return x + y
|
| Parameter specification variables can be introspected. e.g.::
|
| >>> P = ParamSpec("P")
| >>> P.__name__
| 'P'
|
| Note that only parameter specification variables defined in the global
| scope can be pickled.
|
| Methods defined here:
|
| __mro_entries__(...)
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __typing_prepare_subst__(self, /, alias, args)
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __bound__
|
| __contravariant__
|
| __covariant__
|
| __infer_variance__
|
| args
| Represents positional arguments.
|
| kwargs
| Represents keyword arguments.
class ParamSpecArgs(builtins.object)
| The args for a ParamSpec object.
|
| Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
|
| ParamSpecArgs objects have a reference back to their ParamSpec::
|
| >>> P = ParamSpec("P")
| >>> P.args.__origin__ is P
| True
|
| This type is meant for runtime introspection and has no special meaning
| to static type checkers.
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mro_entries__(...)
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __origin__
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class ParamSpecKwargs(builtins.object)
| The kwargs for a ParamSpec object.
|
| Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
|
| ParamSpecKwargs objects have a reference back to their ParamSpec::
|
| >>> P = ParamSpec("P")
| >>> P.kwargs.__origin__ is P
| True
|
| This type is meant for runtime introspection and has no special meaning
| to static type checkers.
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mro_entries__(...)
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __origin__
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class Protocol(Generic)
| Base class for protocol classes.
|
| Protocol classes are defined as::
|
| class Proto(Protocol):
| def meth(self) -> int:
| ...
|
| Such classes are primarily used with static type checkers that recognize
| structural subtyping (static duck-typing).
|
| For example::
|
| class C:
| def meth(self) -> int:
| return 0
|
| def func(x: Proto) -> int:
| return x.meth()
|
| func(C()) # Passes static type check
|
| See PEP 544 for details. Protocol classes decorated with
| @typing.runtime_checkable act as simple-minded runtime protocols that check
| only the presence of given attributes, ignoring their type signatures.
| Protocol classes can be generic, they are defined as::
|
| class GenProto[T](Protocol):
| def meth(self) -> T:
| ...
|
| Method resolution order:
| Protocol
| Generic
| builtins.object
|
| Class methods defined here:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __parameters__ = ()
|
| __protocol_attrs__ = set()
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsAbs(Protocol)
| SupportsAbs(*args, **kwargs)
|
| An ABC with one abstract method __abs__ that is covariant in its return type.
|
| Method resolution order:
| SupportsAbs
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __abs__(self) -> T
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__abs__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __orig_bases__ = (<class 'typing.Protocol'>, typing.Generic[T])
|
| __parameters__ = (T,)
|
| __protocol_attrs__ = {'__abs__'}
|
| __type_params__ = (T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsBytes(Protocol)
| SupportsBytes(*args, **kwargs)
|
| An ABC with one abstract method __bytes__.
|
| Method resolution order:
| SupportsBytes
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __bytes__(self) -> bytes
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__bytes__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__bytes__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsComplex(Protocol)
| SupportsComplex(*args, **kwargs)
|
| An ABC with one abstract method __complex__.
|
| Method resolution order:
| SupportsComplex
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __complex__(self) -> complex
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__complex__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__complex__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsFloat(Protocol)
| SupportsFloat(*args, **kwargs)
|
| An ABC with one abstract method __float__.
|
| Method resolution order:
| SupportsFloat
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __float__(self) -> float
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__float__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__float__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsIndex(Protocol)
| SupportsIndex(*args, **kwargs)
|
| An ABC with one abstract method __index__.
|
| Method resolution order:
| SupportsIndex
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __index__(self) -> int
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__index__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__index__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsInt(Protocol)
| SupportsInt(*args, **kwargs)
|
| An ABC with one abstract method __int__.
|
| Method resolution order:
| SupportsInt
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| __int__(self) -> int
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__int__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__int__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsRound(Protocol)
| SupportsRound(*args, **kwargs)
|
| An ABC with one abstract method __round__ that is covariant in its return type.
|
| Method resolution order:
| SupportsRound
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| __round__(self, ndigits: int = 0) -> T
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__round__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __orig_bases__ = (<class 'typing.Protocol'>, typing.Generic[T])
|
| __parameters__ = (T,)
|
| __protocol_attrs__ = {'__round__'}
|
| __type_params__ = (T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
Text = class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
class TextIO(IO)
| Typed version of the return of open() in text mode.
|
| Method resolution order:
| TextIO
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'TextIO'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| buffer
|
| encoding
|
| errors
|
| line_buffering
|
| newlines
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.IO[str],)
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from IO:
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| write(self, s: ~AnyStr) -> int
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties inherited from IO:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class TypeAliasType(builtins.object)
| Type alias.
|
| Type aliases are created through the type statement::
|
| type Alias = int
|
| In this example, Alias and int will be treated equivalently by static
| type checkers.
|
| At runtime, Alias is an instance of TypeAliasType. The __name__
| attribute holds the name of the type alias. The value of the type alias
| is stored in the __value__ attribute. It is evaluated lazily, so the
| value is computed only if the attribute is accessed.
|
| Type aliases can also be generic::
|
| type ListOrSet[T] = list[T] | set[T]
|
| In this case, the type parameters of the alias are stored in the
| __type_params__ attribute.
|
| See PEP 695 for more information.
|
| Methods defined here:
|
| __getitem__(self, key, /)
| Return self[key].
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __parameters__
|
| __type_params__
|
| __value__
class TypeVar(builtins.object)
| Type variable.
|
| The preferred way to construct a type variable is via the dedicated
| syntax for generic functions, classes, and type aliases::
|
| class Sequence[T]: # T is a TypeVar
| ...
|
| This syntax can also be used to create bound and constrained type
| variables::
|
| # S is a TypeVar bound to str
| class StrSequence[S: str]:
| ...
|
| # A is a TypeVar constrained to str or bytes
| class StrOrBytesSequence[A: (str, bytes)]:
| ...
|
| However, if desired, reusable type variables can also be constructed
| manually, like so::
|
| T = TypeVar('T') # Can be anything
| S = TypeVar('S', bound=str) # Can be any subtype of str
| A = TypeVar('A', str, bytes) # Must be exactly str or bytes
|
| Type variables exist primarily for the benefit of static type
| checkers. They serve as the parameters for generic types as well
| as for generic function and type alias definitions.
|
| The variance of type variables is inferred by type checkers when they
| are created through the type parameter syntax and when
| ``infer_variance=True`` is passed. Manually created type variables may
| be explicitly marked covariant or contravariant by passing
| ``covariant=True`` or ``contravariant=True``. By default, manually
| created type variables are invariant. See PEP 484 and PEP 695 for more
| details.
|
| Methods defined here:
|
| __mro_entries__(...)
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __bound__
|
| __constraints__
|
| __contravariant__
|
| __covariant__
|
| __infer_variance__
class TypeVarTuple(builtins.object)
| Type variable tuple. A specialized form of type variable that enables
| variadic generics.
|
| The preferred way to construct a type variable tuple is via the
| dedicated syntax for generic functions, classes, and type aliases,
| where a single '*' indicates a type variable tuple::
|
| def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
| return (*tup[1:], tup[0])
|
| For compatibility with Python 3.11 and earlier, TypeVarTuple objects
| can also be created as follows::
|
| Ts = TypeVarTuple('Ts') # Can be given any name
|
| Just as a TypeVar (type variable) is a placeholder for a single type,
| a TypeVarTuple is a placeholder for an *arbitrary* number of types. For
| example, if we define a generic class using a TypeVarTuple::
|
| class C[*Ts]: ...
|
| Then we can parameterize that class with an arbitrary number of type
| arguments::
|
| C[int] # Fine
| C[int, str] # Also fine
| C[()] # Even this is fine
|
| For more details, see PEP 646.
|
| Note that only TypeVarTuples defined in the global scope can be
| pickled.
|
| Methods defined here:
|
| __iter__(self, /)
| Implement iter(self).
|
| __mro_entries__(...)
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __typing_prepare_subst__(self, /, alias, args)
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
FUNCTIONS
NamedTuple(typename, fields=None, /, **kwargs)
Typed version of namedtuple.
Usage::
class Employee(NamedTuple):
name: str
id: int
This is equivalent to::
Employee = collections.namedtuple('Employee', ['name', 'id'])
The resulting class has an extra __annotations__ attribute, giving a
dict that maps field names to types. (The field names are also in
the _fields attribute, which is part of the namedtuple API.)
An alternative equivalent functional syntax is also accepted::
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
TypedDict(typename, fields=None, /, *, total=True, **kwargs)
A simple typed namespace. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type such that a type checker will expect all
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime.
Usage::
>>> class Point2D(TypedDict):
... x: int
... y: int
... label: str
...
>>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
>>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
>>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
True
The type info can be accessed via the Point2D.__annotations__ dict, and
the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
TypedDict supports an additional equivalent form::
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
By default, all keys must be present in a TypedDict. It is possible
to override this by specifying totality::
class Point2D(TypedDict, total=False):
x: int
y: int
This means that a Point2D TypedDict can have any of the keys omitted. A type
checker is only expected to support a literal False or True as the value of
the total argument. True is the default, and makes all items defined in the
class body be required.
The Required and NotRequired special forms can also be used to mark
individual keys as being required or not required::
class Point2D(TypedDict):
x: int # the "x" key must always be present (Required is the default)
y: NotRequired[int] # the "y" key can be omitted
See PEP 655 for more details on Required and NotRequired.
assert_never(arg: Never, /) -> Never
Statically assert that a line of code is unreachable.
Example::
def int_or_str(arg: int | str) -> None:
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
assert_never(arg)
If a type checker finds that a call to assert_never() is
reachable, it will emit an error.
At runtime, this throws an exception when called.
assert_type(val, typ, /)
Ask a static type checker to confirm that the value is of the given type.
At runtime this does nothing: it returns the first argument unchanged with no
checks or side effects, no matter the actual type of the argument.
When a static type checker encounters a call to assert_type(), it
emits an error if the value is not of the specified type::
def greet(name: str) -> None:
assert_type(name, str) # OK
assert_type(name, int) # type checker error
cast(typ, val)
Cast a value to a type.
This returns the value unchanged. To the type checker this
signals that the return value has the designated type, but at
runtime we intentionally don't check anything (we want this
to be as fast as possible).
clear_overloads()
Clear all overloads in the registry.
dataclass_transform(*, eq_default: bool = True, order_default: bool = False, kw_only_default: bool = False, frozen_default: bool = False, field_specifiers: tuple[typing.Union[type[typing.Any], typing.Callable[..., typing.Any]], ...] = (), **kwargs: Any) -> <class '_IdentityCallable'>
Decorator to mark an object as providing dataclass-like behaviour.
The decorator can be applied to a function, class, or metaclass.
Example usage with a decorator function::
@dataclass_transform()
def create_model[T](cls: type[T]) -> type[T]:
...
return cls
@create_model
class CustomerModel:
id: int
name: str
On a base class::
@dataclass_transform()
class ModelBase: ...
class CustomerModel(ModelBase):
id: int
name: str
On a metaclass::
@dataclass_transform()
class ModelMeta(type): ...
class ModelBase(metaclass=ModelMeta): ...
class CustomerModel(ModelBase):
id: int
name: str
The ``CustomerModel`` classes defined above will
be treated by type checkers similarly to classes created with
``@dataclasses.dataclass``.
For example, type checkers will assume these classes have
``__init__`` methods that accept ``id`` and ``name``.
The arguments to this decorator can be used to customize this behavior:
- ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
``True`` or ``False`` if it is omitted by the caller.
- ``order_default`` indicates whether the ``order`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``kw_only_default`` indicates whether the ``kw_only`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``frozen_default`` indicates whether the ``frozen`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``field_specifiers`` specifies a static list of supported classes
or functions that describe fields, similar to ``dataclasses.field()``.
- Arbitrary other keyword arguments are accepted in order to allow for
possible future extensions.
At runtime, this decorator records its arguments in the
``__dataclass_transform__`` attribute on the decorated object.
It has no other runtime effect.
See PEP 681 for more details.
final(f)
Decorator to indicate final methods and final classes.
Use this decorator to indicate to type checkers that the decorated
method cannot be overridden, and decorated class cannot be subclassed.
For example::
class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...
There is no runtime checking of these properties. The decorator
attempts to set the ``__final__`` attribute to ``True`` on the decorated
object to allow runtime introspection.
get_args(tp)
Get type arguments with all substitutions performed.
For unions, basic simplifications used by Union constructor are performed.
Examples::
>>> T = TypeVar('T')
>>> assert get_args(Dict[str, int]) == (str, int)
>>> assert get_args(int) == ()
>>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
>>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
>>> assert get_args(Callable[[], T][int]) == ([], int)
get_origin(tp)
Get the unsubscripted version of a type.
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
Annotated, and others. Return None for unsupported types.
Examples::
>>> P = ParamSpec('P')
>>> assert get_origin(Literal[42]) is Literal
>>> assert get_origin(int) is None
>>> assert get_origin(ClassVar[int]) is ClassVar
>>> assert get_origin(Generic) is Generic
>>> assert get_origin(Generic[T]) is Generic
>>> assert get_origin(Union[T, int]) is Union
>>> assert get_origin(List[Tuple[T, T]][int]) is list
>>> assert get_origin(P.args) is P
get_overloads(func)
Return all defined overloads for *func* as a sequence.
get_type_hints(obj, globalns=None, localns=None, include_extras=False)
Return type hints for an object.
This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals and recursively replaces all
'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
The argument may be a module, class, method, or function. The annotations
are returned as a dictionary. For classes, annotations include also
inherited members.
TypeError is raised if the argument is not of a type that can contain
annotations, and an empty dictionary is returned if no annotations are
present.
BEWARE -- the behavior of globalns and localns is counterintuitive
(unless you are familiar with how eval() and exec() work). The
search order is locals first, then globals.
- If no dict arguments are passed, an attempt is made to use the
globals from obj (or the respective module's globals for classes),
and these are also used as the locals. If the object does not appear
to have globals, an empty dictionary is used. For classes, the search
order is globals first then locals.
- If one dict argument is passed, it is used for both globals and
locals.
- If two dict arguments are passed, they specify globals and
locals, respectively.
is_typeddict(tp)
Check if an annotation is a TypedDict class.
For example::
>>> from typing import TypedDict
>>> class Film(TypedDict):
... title: str
... year: int
...
>>> is_typeddict(Film)
True
>>> is_typeddict(dict)
False
no_type_check(arg)
Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses).
This mutates the function(s) or class(es) in place.
no_type_check_decorator(decorator)
Decorator to give another decorator the @no_type_check effect.
This wraps the decorator with something that wraps the decorated
function in @no_type_check.
overload(func)
Decorator for overloaded functions/methods.
In a stub file, place two or more stub definitions for the same
function in a row, each decorated with @overload.
For example::
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
In a non-stub file (i.e. a regular .py file), do the same but
follow it with an implementation. The implementation should *not*
be decorated with @overload::
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
def utf8(value):
... # implementation goes here
The overloads for a function can be retrieved at runtime using the
get_overloads() function.
override(method: F, /) -> F
Indicate that a method is intended to override a method in a base class.
Usage::
class Base:
def method(self) -> None:
pass
class Child(Base):
@override
def method(self) -> None:
super().method()
When this decorator is applied to a method, the type checker will
validate that it overrides a method or attribute with the same name on a
base class. This helps prevent bugs that may occur when a base class is
changed without an equivalent change to a child class.
There is no runtime checking of this property. The decorator attempts to
set the ``__override__`` attribute to ``True`` on the decorated object to
allow runtime introspection.
See PEP 698 for details.
reveal_type(obj: T, /) -> T
Ask a static type checker to reveal the inferred type of an expression.
When a static type checker encounters a call to ``reveal_type()``,
it will emit the inferred type of the argument::
x: int = 1
reveal_type(x)
Running a static type checker (e.g., mypy) on this example
will produce output similar to 'Revealed type is "builtins.int"'.
At runtime, the function prints the runtime type of the
argument and returns the argument unchanged.
runtime_checkable(cls)
Mark a protocol class as a runtime protocol.
Such protocol can be used with isinstance() and issubclass().
Raise TypeError if applied to a non-protocol class.
This allows a simple-minded structural check very similar to
one trick ponies in collections.abc such as Iterable.
For example::
@runtime_checkable
class Closable(Protocol):
def close(self): ...
assert isinstance(open('/some/file'), Closable)
Warning: this will check only the presence of the required methods,
not their type signatures!
DATA
AbstractSet = typing.AbstractSet
A generic version of collections.abc.Set.
AnyStr = ~AnyStr
AsyncContextManager = typing.AsyncContextManager
A generic version of contextlib.AbstractAsyncContextManager.
AsyncGenerator = typing.AsyncGenerator
A generic version of collections.abc.AsyncGenerator.
AsyncIterable = typing.AsyncIterable
A generic version of collections.abc.AsyncIterable.
AsyncIterator = typing.AsyncIterator
A generic version of collections.abc.AsyncIterator.
Awaitable = typing.Awaitable
A generic version of collections.abc.Awaitable.
ByteString = typing.ByteString
A generic version of collections.abc.ByteString.
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
ChainMap = typing.ChainMap
A generic version of collections.ChainMap.
ClassVar = typing.ClassVar
Special type construct to mark class variables.
An annotation wrapped in ClassVar indicates that a given
attribute is intended to be used as a class variable and
should not be set on instances of that class.
Usage::
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
ClassVar accepts only types and cannot be further subscribed.
Note that ClassVar is not a class itself, and should not
be used with isinstance() or issubclass().
Collection = typing.Collection
A generic version of collections.abc.Collection.
Concatenate = typing.Concatenate
Special form for annotating higher-order functions.
``Concatenate`` can be used in conjunction with ``ParamSpec`` and
``Callable`` to represent a higher-order function which adds, removes or
transforms the parameters of a callable.
For example::
Callable[Concatenate[int, P], int]
See PEP 612 for detailed information.
Container = typing.Container
A generic version of collections.abc.Container.
ContextManager = typing.ContextManager
A generic version of contextlib.AbstractContextManager.
Coroutine = typing.Coroutine
A generic version of collections.abc.Coroutine.
Counter = typing.Counter
A generic version of collections.Counter.
DefaultDict = typing.DefaultDict
A generic version of collections.defaultdict.
Deque = typing.Deque
A generic version of collections.deque.
Dict = typing.Dict
A generic version of dict.
Final = typing.Final
Special typing construct to indicate final names to type checkers.
A final name cannot be re-assigned or overridden in a subclass.
For example::
MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
TIMEOUT = 1 # Error reported by type checker
There is no runtime checking of these properties.
FrozenSet = typing.FrozenSet
A generic version of frozenset.
Generator = typing.Generator
A generic version of collections.abc.Generator.
Hashable = typing.Hashable
A generic version of collections.abc.Hashable.
ItemsView = typing.ItemsView
A generic version of collections.abc.ItemsView.
Iterable = typing.Iterable
A generic version of collections.abc.Iterable.
Iterator = typing.Iterator
A generic version of collections.abc.Iterator.
KeysView = typing.KeysView
A generic version of collections.abc.KeysView.
List = typing.List
A generic version of list.
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
LiteralString = typing.LiteralString
Represents an arbitrary literal string.
Example::
from typing import LiteralString
def run_query(sql: LiteralString) -> None:
...
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # OK
run_query(literal_string) # OK
run_query("SELECT * FROM " + literal_string) # OK
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
Only string literals and other LiteralStrings are compatible
with LiteralString. This provides a tool to help prevent
security issues such as SQL injection.
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
MappingView = typing.MappingView
A generic version of collections.abc.MappingView.
Match = typing.Match
A generic version of re.Match.
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
MutableSequence = typing.MutableSequence
A generic version of collections.abc.MutableSequence.
MutableSet = typing.MutableSet
A generic version of collections.abc.MutableSet.
Never = typing.Never
The bottom type, a type that has no members.
This can be used to define a function that should never be
called, or a function that never returns::
from typing import Never
def never_call_me(arg: Never) -> None:
pass
def int_or_str(arg: int | str) -> None:
never_call_me(arg) # type checker error
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
never_call_me(arg) # OK, arg is of type Never
NoReturn = typing.NoReturn
Special type indicating functions that never return.
Example::
from typing import NoReturn
def stop() -> NoReturn:
raise Exception('no way')
NoReturn can also be used as a bottom type, a type that
has no values. Starting in Python 3.11, the Never type should
be used for this concept instead. Type checkers should treat the two
equivalently.
NotRequired = typing.NotRequired
Special typing construct to mark a TypedDict key as potentially missing.
For example::
class Movie(TypedDict):
title: str
year: NotRequired[int]
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
OrderedDict = typing.OrderedDict
A generic version of collections.OrderedDict.
Pattern = typing.Pattern
A generic version of re.Pattern.
Required = typing.Required
Special typing construct to mark a TypedDict key as required.
This is mainly useful for total=False TypedDicts.
For example::
class Movie(TypedDict, total=False):
title: Required[str]
year: int
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
There is no runtime checking that a required key is actually provided
when instantiating a related TypedDict.
Reversible = typing.Reversible
A generic version of collections.abc.Reversible.
Self = typing.Self
Used to spell the type of "self" in classes.
Example::
from typing import Self
class Foo:
def return_self(self) -> Self:
...
return self
This is especially useful for:
- classmethods that are used as alternative constructors
- annotating an `__enter__` method which returns self
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
Set = typing.Set
A generic version of set.
Sized = typing.Sized
A generic version of collections.abc.Sized.
TYPE_CHECKING = False
Tuple = typing.Tuple
Deprecated alias to builtins.tuple.
Tuple[X, Y] is the cross-product type of X and Y.
Example: Tuple[T1, T2] is a tuple of two elements corresponding
to type variables T1 and T2. Tuple[int, float, str] is a tuple
of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
Type = typing.Type
Deprecated alias to builtins.type.
builtins.type or typing.Type can be used to annotate class objects.
For example, suppose we have the following classes::
class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::
def new_user[U](user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user
joe = new_user(BasicUser)
At this point the type checker knows that joe has type BasicUser.
TypeAlias = typing.TypeAlias
Special form for marking type aliases.
Use TypeAlias to indicate that an assignment should
be recognized as a proper type alias definition by type
checkers.
For example::
Predicate: TypeAlias = Callable[..., bool]
It's invalid when used anywhere except as in the example above.
TypeGuard = typing.TypeGuard
Special typing construct for marking user-defined type guard functions.
``TypeGuard`` can be used to annotate the return type of a user-defined
type guard function. ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
type checkers to determine a more precise type of an expression within a
program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "type guard".
Sometimes it would be convenient to use a user-defined boolean function
as a type guard. Such a function should use ``TypeGuard[...]`` as its
return type to alert static type checkers to this intention.
Using ``-> TypeGuard`` tells the static type checker that for a given
function:
1. The return value is a boolean.
2. If the return value is ``True``, the type of its argument
is the type inside ``TypeGuard``.
For example::
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: list[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``list[str]``.
print(" ".join(val))
else:
# Type of ``val`` remains as ``list[object]``.
print("Not a list of strings!")
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
form of ``TypeA`` (it can even be a wider form) and this may lead to
type-unsafe results. The main reason is to allow for things like
narrowing ``list[object]`` to ``list[str]`` even though the latter is not
a subtype of the former, since ``list`` is invariant. The responsibility of
writing type-safe type guards is left to the user.
``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
Unpack = typing.Unpack
Type unpack operator.
The type unpack operator takes the child types from some container type,
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
For example::
# For some generic class `Foo`:
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
Ts = TypeVarTuple('Ts')
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
# `Generic[]`.)
class Bar(Generic[Unpack[Ts]]): ...
Bar[int] # Valid
Bar[int, str] # Also valid
From Python 3.11, this can also be done using the `*` operator::
Foo[*tuple[int, str]]
class Bar(Generic[*Ts]): ...
And from Python 3.12, it can be done using built-in syntax for generics::
Foo[*tuple[int, str]]
class Bar[*Ts]: ...
The operator can also be used along with a `TypedDict` to annotate
`**kwargs` in a function signature::
class Movie(TypedDict):
name: str
year: int
# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
Note that there is only some runtime checking of this operator. Not
everything the runtime allows may be accepted by static type checkers.
For more information, see PEPs 646 and 692.
ValuesView = typing.ValuesView
A generic version of collections.abc.ValuesView.
__all__ = ['Annotated', 'Any', 'Callable', 'ClassVar', 'Concatenate', ...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\typing.py
flask.template_rendered
Python Library Documentation: NamedSignal in module blinker.base object
class NamedSignal(Signal)
| NamedSignal(name: 'str', doc: 'str | None' = None) -> 'None'
|
| A named generic notification emitter. The name is not used by the signal
| itself, but matches the key in the :class:`Namespace` that it belongs to.
|
| :param name: The name of the signal within the namespace.
| :param doc: The docstring for the signal.
|
| Method resolution order:
| NamedSignal
| Signal
| builtins.object
|
| Methods defined here:
|
| __init__(self, name: 'str', doc: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Signal:
|
| connect(self, receiver: 'F', sender: 't.Any' = ANY, weak: 'bool' = True) -> 'F'
| Connect ``receiver`` to be called when the signal is sent by
| ``sender``.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.
|
| connect_via(self, sender: 't.Any', weak: 'bool' = False) -> 'c.Callable[[F], F]'
| Connect the decorated function to be called when the signal is sent
| by ``sender``.
|
| The decorated function will be called when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument along
| with any extra keyword arguments.
|
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender. A receiver may be connected
| to multiple senders by calling :meth:`connect` multiple times.
| :param weak: Track the receiver with a :mod:`weakref`. The receiver will
| be automatically disconnected when it is garbage collected. When
| connecting a receiver defined within a function, set to ``False``,
| otherwise it will be disconnected when the function scope ends.=
|
| .. versionadded:: 1.1
|
| connected_to(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'c.Generator[None, None, None]'
| A context manager that temporarily connects ``receiver`` to the
| signal while a ``with`` block executes. When the block exits, the
| receiver is disconnected. Useful for tests.
|
| :param receiver: The callable to call when :meth:`send` is called with
| the given ``sender``, passing ``sender`` as a positional argument
| along with any extra keyword arguments.
| :param sender: Any object or :data:`ANY`. ``receiver`` will only be
| called when :meth:`send` is called with this sender. If ``ANY``, the
| receiver will be called for any sender.
|
| .. versionadded:: 1.1
|
| disconnect(self, receiver: 'c.Callable[..., t.Any]', sender: 't.Any' = ANY) -> 'None'
| Disconnect ``receiver`` from being called when the signal is sent by
| ``sender``.
|
| :param receiver: A connected receiver callable.
| :param sender: Disconnect from only this sender. By default, disconnect
| from all senders.
|
| has_receivers_for(self, sender: 't.Any') -> 'bool'
| Check if there is at least one receiver that will be called with the
| given ``sender``. A receiver connected to :data:`ANY` will always be
| called, regardless of sender. Does not check if weakly referenced
| receivers are still live. See :meth:`receivers_for` for a stronger
| search.
|
| :param sender: Check for receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| muted(self) -> 'c.Generator[None, None, None]'
| A context manager that temporarily disables the signal. No receivers
| will be called if the signal is sent, until the ``with`` block exits.
| Useful for tests.
|
| receiver_connected = <functools.cached_property object>
| Emitted at the end of each :meth:`connect` call.
|
| The signal sender is the signal instance, and the :meth:`connect`
| arguments are passed through: ``receiver``, ``sender``, and ``weak``.
|
| .. versionadded:: 1.2
|
| receiver_disconnected = <functools.cached_property object>
| Emitted at the end of each :meth:`disconnect` call.
|
| The sender is the signal instance, and the :meth:`disconnect` arguments
| are passed through: ``receiver`` and ``sender``.
|
| This signal is emitted **only** when :meth:`disconnect` is called
| explicitly. This signal cannot be emitted by an automatic disconnect
| when a weakly referenced receiver or sender goes out of scope, as the
| instance is no longer be available to be used as the sender for this
| signal.
|
| An alternative approach is available by subscribing to
| :attr:`receiver_connected` and setting up a custom weakref cleanup
| callback on weak receivers and senders.
|
| .. versionadded:: 1.2
|
| receivers_for(self, sender: 't.Any') -> 'c.Generator[c.Callable[..., t.Any], None, None]'
| Yield each receiver to be called for ``sender``, in addition to those
| to be called for :data:`ANY`. Weakly referenced receivers that are not
| live will be disconnected and skipped.
|
| :param sender: Yield receivers connected to this sender, in addition
| to those connected to :data:`ANY`.
|
| send(self, sender: 't.Any | None' = None, /, *, _async_wrapper: 'c.Callable[[c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Call all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _async_wrapper: Will be called on any receivers that are async
| coroutines to turn them into sync callables. For example, could run
| the receiver with an event loop.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionchanged:: 1.7
| Added the ``_async_wrapper`` argument.
|
| async send_async(self, sender: 't.Any | None' = None, /, *, _sync_wrapper: 'c.Callable[[c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]] | None' = None, **kwargs: 't.Any') -> 'list[tuple[c.Callable[..., t.Any], t.Any]]'
| Await all receivers that are connected to the given ``sender``
| or :data:`ANY`. Each receiver is called with ``sender`` as a positional
| argument along with any extra keyword arguments. Return a list of
| ``(receiver, return value)`` tuples.
|
| The order receivers are called is undefined, but can be influenced by
| setting :attr:`set_class`.
|
| If a receiver raises an exception, that exception will propagate up.
| This makes debugging straightforward, with an assumption that correctly
| implemented receivers will not raise.
|
| :param sender: Call receivers connected to this sender, in addition to
| those connected to :data:`ANY`.
| :param _sync_wrapper: Will be called on any receivers that are sync
| callables to turn them into async coroutines. For example,
| could call the receiver in a thread.
| :param kwargs: Extra keyword arguments to pass to each receiver.
|
| .. versionadded:: 1.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Signal:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Signal:
|
| ANY = ANY
|
| set_class = <class 'set'>
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
flask.templating
Python Library Documentation: module flask.templating in flask
NAME
flask.templating
CLASSES
jinja2.environment.Environment(builtins.object)
Environment
jinja2.loaders.BaseLoader(builtins.object)
DispatchingJinjaLoader
class DispatchingJinjaLoader(jinja2.loaders.BaseLoader)
| DispatchingJinjaLoader(app: 'App') -> 'None'
|
| A loader that looks for templates in the application and all
| the blueprint folders.
|
| Method resolution order:
| DispatchingJinjaLoader
| jinja2.loaders.BaseLoader
| builtins.object
|
| Methods defined here:
|
| __init__(self, app: 'App') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| get_source(self, environment: 'BaseEnvironment', template: 'str') -> 'tuple[str, str | None, t.Callable[[], bool] | None]'
| Get the template source, filename and reload helper for a template.
| It's passed the environment and template name and has to return a
| tuple in the form ``(source, filename, uptodate)`` or raise a
| `TemplateNotFound` error if it can't locate the template.
|
| The source part of the returned tuple must be the source of the
| template as a string. The filename should be the name of the
| file on the filesystem if it was loaded from there, otherwise
| ``None``. The filename is used by Python for the tracebacks
| if no loader extension is used.
|
| The last item in the tuple is the `uptodate` function. If auto
| reloading is enabled it's always called to check if the template
| changed. No arguments are passed so the function must store the
| old state somewhere (for example in a closure). If it returns `False`
| the template will be reloaded.
|
| list_templates(self) -> 'list[str]'
| Iterates over all templates. If the loader does not support that
| it should raise a :exc:`TypeError` which is the default behavior.
|
| ----------------------------------------------------------------------
| Methods inherited from jinja2.loaders.BaseLoader:
|
| load(self, environment: 'Environment', name: str, globals: Optional[MutableMapping[str, Any]] = None) -> 'Template'
| Loads a template. This method looks up the template in the cache
| or loads one by calling :meth:`get_source`. Subclasses should not
| override this method as loaders working on collections of other
| loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
| will not call this method but `get_source` directly.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from jinja2.loaders.BaseLoader:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from jinja2.loaders.BaseLoader:
|
| has_source_access = True
class Environment(jinja2.environment.Environment)
| Environment(app: 'App', **options: 't.Any') -> 'None'
|
| Works like a regular Jinja environment but has some additional
| knowledge of how Flask's blueprint works so that it can prepend the
| name of the blueprint to referenced templates if necessary.
|
| Method resolution order:
| Environment
| jinja2.environment.Environment
| builtins.object
|
| Methods defined here:
|
| __init__(self, app: 'App', **options: 't.Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from jinja2.environment.Environment:
|
| add_extension(self, extension: Union[str, Type[ForwardRef('Extension')]]) -> None
| Adds an extension after the environment was created.
|
| .. versionadded:: 2.5
|
| call_filter(self, name: str, value: Any, args: Optional[Sequence[Any]] = None, kwargs: Optional[Mapping[str, Any]] = None, context: Optional[jinja2.runtime.Context] = None, eval_ctx: Optional[jinja2.nodes.EvalContext] = None) -> Any
| Invoke a filter on a value the same way the compiler does.
|
| This might return a coroutine if the filter is running from an
| environment in async mode and the filter supports async
| execution. It's your responsibility to await this if needed.
|
| .. versionadded:: 2.7
|
| call_test(self, name: str, value: Any, args: Optional[Sequence[Any]] = None, kwargs: Optional[Mapping[str, Any]] = None, context: Optional[jinja2.runtime.Context] = None, eval_ctx: Optional[jinja2.nodes.EvalContext] = None) -> Any
| Invoke a test on a value the same way the compiler does.
|
| This might return a coroutine if the test is running from an
| environment in async mode and the test supports async execution.
| It's your responsibility to await this if needed.
|
| .. versionchanged:: 3.0
| Tests support ``@pass_context``, etc. decorators. Added
| the ``context`` and ``eval_ctx`` parameters.
|
| .. versionadded:: 2.7
|
| compile(self, source: Union[str, jinja2.nodes.Template], name: Optional[str] = None, filename: Optional[str] = None, raw: bool = False, defer_init: bool = False) -> Union[str, code]
| Compile a node or template source code. The `name` parameter is
| the load name of the template after it was joined using
| :meth:`join_path` if necessary, not the filename on the file system.
| the `filename` parameter is the estimated filename of the template on
| the file system. If the template came from a database or memory this
| can be omitted.
|
| The return value of this method is a python code object. If the `raw`
| parameter is `True` the return value will be a string with python
| code equivalent to the bytecode returned otherwise. This method is
| mainly used internally.
|
| `defer_init` is use internally to aid the module code generator. This
| causes the generated code to be able to import without the global
| environment variable to be set.
|
| .. versionadded:: 2.4
| `defer_init` parameter added.
|
| compile_expression(self, source: str, undefined_to_none: bool = True) -> 'TemplateExpression'
| A handy helper method that returns a callable that accepts keyword
| arguments that appear as variables in the expression. If called it
| returns the result of the expression.
|
| This is useful if applications want to use the same rules as Jinja
| in template "configuration files" or similar situations.
|
| Example usage:
|
| >>> env = Environment()
| >>> expr = env.compile_expression('foo == 42')
| >>> expr(foo=23)
| False
| >>> expr(foo=42)
| True
|
| Per default the return value is converted to `None` if the
| expression returns an undefined value. This can be changed
| by setting `undefined_to_none` to `False`.
|
| >>> env.compile_expression('var')() is None
| True
| >>> env.compile_expression('var', undefined_to_none=False)()
| Undefined
|
| .. versionadded:: 2.1
|
| compile_templates(self, target: Union[str, ForwardRef('os.PathLike[str]')], extensions: Optional[Collection[str]] = None, filter_func: Optional[Callable[[str], bool]] = None, zip: Optional[str] = 'deflated', log_function: Optional[Callable[[str], NoneType]] = None, ignore_errors: bool = True) -> None
| Finds all the templates the loader can find, compiles them
| and stores them in `target`. If `zip` is `None`, instead of in a
| zipfile, the templates will be stored in a directory.
| By default a deflate zip algorithm is used. To switch to
| the stored algorithm, `zip` can be set to ``'stored'``.
|
| `extensions` and `filter_func` are passed to :meth:`list_templates`.
| Each template returned will be compiled to the target folder or
| zipfile.
|
| By default template compilation errors are ignored. In case a
| log function is provided, errors are logged. If you want template
| syntax errors to abort the compilation you can set `ignore_errors`
| to `False` and you will get an exception on syntax errors.
|
| .. versionadded:: 2.4
|
| extend(self, **attributes: Any) -> None
| Add the items to the instance of the environment if they do not exist
| yet. This is used by :ref:`extensions <writing-extensions>` to register
| callbacks and configuration values without breaking inheritance.
|
| from_string(self, source: Union[str, jinja2.nodes.Template], globals: Optional[MutableMapping[str, Any]] = None, template_class: Optional[Type[ForwardRef('Template')]] = None) -> 'Template'
| Load a template from a source string without using
| :attr:`loader`.
|
| :param source: Jinja source to compile into a template.
| :param globals: Extend the environment :attr:`globals` with
| these extra variables available for all renders of this
| template. If the template has already been loaded and
| cached, its globals are updated with any new items.
| :param template_class: Return an instance of this
| :class:`Template` class.
|
| get_or_select_template(self, template_name_or_list: Union[str, ForwardRef('Template'), List[Union[str, ForwardRef('Template')]]], parent: Optional[str] = None, globals: Optional[MutableMapping[str, Any]] = None) -> 'Template'
| Use :meth:`select_template` if an iterable of template names
| is given, or :meth:`get_template` if one name is given.
|
| .. versionadded:: 2.3
|
| get_template(self, name: Union[str, ForwardRef('Template')], parent: Optional[str] = None, globals: Optional[MutableMapping[str, Any]] = None) -> 'Template'
| Load a template by name with :attr:`loader` and return a
| :class:`Template`. If the template does not exist a
| :exc:`TemplateNotFound` exception is raised.
|
| :param name: Name of the template to load. When loading
| templates from the filesystem, "/" is used as the path
| separator, even on Windows.
| :param parent: The name of the parent template importing this
| template. :meth:`join_path` can be used to implement name
| transformations with this.
| :param globals: Extend the environment :attr:`globals` with
| these extra variables available for all renders of this
| template. If the template has already been loaded and
| cached, its globals are updated with any new items.
|
| .. versionchanged:: 3.0
| If a template is loaded from cache, ``globals`` will update
| the template's globals instead of ignoring the new values.
|
| .. versionchanged:: 2.4
| If ``name`` is a :class:`Template` object it is returned
| unchanged.
|
| getattr(self, obj: Any, attribute: str) -> Any
| Get an item or attribute of an object but prefer the attribute.
| Unlike :meth:`getitem` the attribute *must* be a string.
|
| getitem(self, obj: Any, argument: Union[str, Any]) -> Union[Any, jinja2.runtime.Undefined]
| Get an item or attribute of an object but prefer the item.
|
| handle_exception(self, source: Optional[str] = None) -> 'te.NoReturn'
| Exception handling helper. This is used internally to either raise
| rewritten exceptions or return a rendered traceback for the template.
|
| iter_extensions(self) -> Iterator[ForwardRef('Extension')]
| Iterates over the extensions by priority.
|
| join_path(self, template: str, parent: str) -> str
| Join a template with the parent. By default all the lookups are
| relative to the loader root so this method returns the `template`
| parameter unchanged, but if the paths should be relative to the
| parent template, this function can be used to calculate the real
| template name.
|
| Subclasses may override this method and implement template path
| joining here.
|
| lex(self, source: str, name: Optional[str] = None, filename: Optional[str] = None) -> Iterator[Tuple[int, str, str]]
| Lex the given sourcecode and return a generator that yields
| tokens as tuples in the form ``(lineno, token_type, value)``.
| This can be useful for :ref:`extension development <writing-extensions>`
| and debugging templates.
|
| This does not perform preprocessing. If you want the preprocessing
| of the extensions to be applied you have to filter source through
| the :meth:`preprocess` method.
|
| list_templates(self, extensions: Optional[Collection[str]] = None, filter_func: Optional[Callable[[str], bool]] = None) -> List[str]
| Returns a list of templates for this environment. This requires
| that the loader supports the loader's
| :meth:`~BaseLoader.list_templates` method.
|
| If there are other files in the template folder besides the
| actual templates, the returned list can be filtered. There are two
| ways: either `extensions` is set to a list of file extensions for
| templates, or a `filter_func` can be provided which is a callable that
| is passed a template name and should return `True` if it should end up
| in the result list.
|
| If the loader does not support that, a :exc:`TypeError` is raised.
|
| .. versionadded:: 2.4
|
| make_globals(self, d: Optional[MutableMapping[str, Any]]) -> MutableMapping[str, Any]
| Make the globals map for a template. Any given template
| globals overlay the environment :attr:`globals`.
|
| Returns a :class:`collections.ChainMap`. This allows any changes
| to a template's globals to only affect that template, while
| changes to the environment's globals are still reflected.
| However, avoid modifying any globals after a template is loaded.
|
| :param d: Dict of template-specific globals.
|
| .. versionchanged:: 3.0
| Use :class:`collections.ChainMap` to always prevent mutating
| environment globals.
|
| overlay(self, block_start_string: str = missing, block_end_string: str = missing, variable_start_string: str = missing, variable_end_string: str = missing, comment_start_string: str = missing, comment_end_string: str = missing, line_statement_prefix: Optional[str] = missing, line_comment_prefix: Optional[str] = missing, trim_blocks: bool = missing, lstrip_blocks: bool = missing, newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing, keep_trailing_newline: bool = missing, extensions: Sequence[Union[str, Type[ForwardRef('Extension')]]] = missing, optimized: bool = missing, undefined: Type[jinja2.runtime.Undefined] = missing, finalize: Optional[Callable[..., Any]] = missing, autoescape: Union[bool, Callable[[Optional[str]], bool]] = missing, loader: Optional[ForwardRef('BaseLoader')] = missing, cache_size: int = missing, auto_reload: bool = missing, bytecode_cache: Optional[ForwardRef('BytecodeCache')] = missing, enable_async: bool = False) -> 'Environment'
| Create a new overlay environment that shares all the data with the
| current environment except for cache and the overridden attributes.
| Extensions cannot be removed for an overlayed environment. An overlayed
| environment automatically gets all the extensions of the environment it
| is linked to plus optional extra extensions.
|
| Creating overlays should happen after the initial environment was set
| up completely. Not all attributes are truly linked, some are just
| copied over so modifications on the original environment may not shine
| through.
|
| .. versionchanged:: 3.1.2
| Added the ``newline_sequence``,, ``keep_trailing_newline``,
| and ``enable_async`` parameters to match ``__init__``.
|
| parse(self, source: str, name: Optional[str] = None, filename: Optional[str] = None) -> jinja2.nodes.Template
| Parse the sourcecode and return the abstract syntax tree. This
| tree of nodes is used by the compiler to convert the template into
| executable source- or bytecode. This is useful for debugging or to
| extract information from templates.
|
| If you are :ref:`developing Jinja extensions <writing-extensions>`
| this gives you a good overview of the node tree generated.
|
| preprocess(self, source: str, name: Optional[str] = None, filename: Optional[str] = None) -> str
| Preprocesses the source with all extensions. This is automatically
| called for all parsing and compiling methods but *not* for :meth:`lex`
| because there you usually only want the actual source tokenized.
|
| select_template(self, names: Iterable[Union[str, ForwardRef('Template')]], parent: Optional[str] = None, globals: Optional[MutableMapping[str, Any]] = None) -> 'Template'
| Like :meth:`get_template`, but tries loading multiple names.
| If none of the names can be loaded a :exc:`TemplatesNotFound`
| exception is raised.
|
| :param names: List of template names to try loading in order.
| :param parent: The name of the parent template importing this
| template. :meth:`join_path` can be used to implement name
| transformations with this.
| :param globals: Extend the environment :attr:`globals` with
| these extra variables available for all renders of this
| template. If the template has already been loaded and
| cached, its globals are updated with any new items.
|
| .. versionchanged:: 3.0
| If a template is loaded from cache, ``globals`` will update
| the template's globals instead of ignoring the new values.
|
| .. versionchanged:: 2.11
| If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
| is raised instead. If no templates were found and ``names``
| contains :class:`Undefined`, the message is more helpful.
|
| .. versionchanged:: 2.4
| If ``names`` contains a :class:`Template` object it is
| returned unchanged.
|
| .. versionadded:: 2.3
|
| ----------------------------------------------------------------------
| Static methods inherited from jinja2.environment.Environment:
|
| concat = join(iterable, /) method of builtins.str instance
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from jinja2.environment.Environment:
|
| lexer
| The lexer for this environment.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from jinja2.environment.Environment:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from jinja2.environment.Environment:
|
| code_generator_class = <class 'jinja2.compiler.CodeGenerator'>
|
| context_class = <class 'jinja2.runtime.Context'>
| The template context holds the variables of a template. It stores the
| values passed to the template and also the names the template exports.
| Creating instances is neither supported nor useful as it's created
| automatically at various stages of the template evaluation and should not
| be created by hand.
|
| The context is immutable. Modifications on :attr:`parent` **must not**
| happen and modifications on :attr:`vars` are allowed from generated
| template code only. Template filters and global functions marked as
| :func:`pass_context` get the active context passed as first argument
| and are allowed to access the context read-only.
|
| The template context supports read only dict operations (`get`,
| `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
| `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
| method that doesn't fail with a `KeyError` but returns an
| :class:`Undefined` object for missing variables.
|
|
| linked_to = None
|
| overlayed = False
|
| sandboxed = False
|
| shared = False
|
| template_class = <class 'jinja2.environment.Template'>
| A compiled template that can be rendered.
|
| Use the methods on :class:`Environment` to create or load templates.
| The environment is used to configure how templates are compiled and
| behave.
|
| It is also possible to create a template object directly. This is
| not usually recommended. The constructor takes most of the same
| arguments as :class:`Environment`. All templates created with the
| same environment arguments share the same ephemeral ``Environment``
| instance behind the scenes.
|
| A template object should be considered immutable. Modifications on
| the object are not supported.
FUNCTIONS
render_template(template_name_or_list: 'str | Template | list[str | Template]', **context: 't.Any') -> 'str'
Render a template by name with the given context.
:param template_name_or_list: The name of the template to render. If
a list is given, the first name to exist will be rendered.
:param context: The variables to make available in the template.
render_template_string(source: 'str', **context: 't.Any') -> 'str'
Render a template from the given source string with the given
context.
:param source: The source code of the template to render.
:param context: The variables to make available in the template.
stream_template(template_name_or_list: 'str | Template | list[str | Template]', **context: 't.Any') -> 't.Iterator[str]'
Render a template by name with the given context as a stream.
This returns an iterator of strings, which can be used as a
streaming response from a view.
:param template_name_or_list: The name of the template to render. If
a list is given, the first name to exist will be rendered.
:param context: The variables to make available in the template.
.. versionadded:: 2.2
stream_template_string(source: 'str', **context: 't.Any') -> 't.Iterator[str]'
Render a template from the given source string with the given
context as a stream. This returns an iterator of strings, which can
be used as a streaming response from a view.
:param source: The source code of the template to render.
:param context: The variables to make available in the template.
.. versionadded:: 2.2
DATA
before_render_template = <blinker.base.NamedSignal object at 0x0000023...
current_app = <LocalProxy unbound>
request = <LocalProxy unbound>
template_rendered = <blinker.base.NamedSignal object at 0x000002320846...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\templating.py
flask.typing
Python Library Documentation: module flask.typing in flask
NAME
flask.typing
DATA
AfterRequestCallable = typing.Union[typing.Callable[[~ResponseClass], ...
AppOrBlueprintKey = typing.Optional[str]
BeforeFirstRequestCallable = typing.Union[typing.Callable[[], NoneType...
BeforeRequestCallable = typing.Union[typing.Callable[[], typing.Union[...
ErrorHandlerCallable = typing.Union[typing.Callable[[typing.Any], typi...
HeaderValue = typing.Union[str, list[str], tuple[str, ...]]
HeadersValue = typing.Union[ForwardRef('Headers'), typing.Mappi... typ...
ResponseClass = ~ResponseClass
ResponseReturnValue = typing.Union[ForwardRef('Response'), str, bytes,...
ResponseValue = typing.Union[ForwardRef('Response'), str, bytes,...rab...
RouteCallable = typing.Union[typing.Callable[..., typing.Union[F...str...
ShellContextProcessorCallable = typing.Callable[[], dict[str, typing.A...
TeardownCallable = typing.Union[typing.Callable[[typing.Optional[Ba......
TemplateContextProcessorCallable = typing.Union[typing.Callable[[], di...
TemplateFilterCallable = typing.Callable[..., typing.Any]
TemplateGlobalCallable = typing.Callable[..., typing.Any]
TemplateTestCallable = typing.Callable[..., bool]
URLDefaultCallable = typing.Callable[[str, dict[str, typing.Any]], Non...
URLValuePreprocessorCallable = typing.Callable[[typing.Optional[str], ...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\typing.py
flask.url_for
Python Library Documentation: function url_for in module flask.helpers
url_for(endpoint: 'str', *, _anchor: 'str | None' = None, _method: 'str | None' = None, _scheme: 'str | None' = None, _external: 'bool | None' = None, **values: 't.Any') -> 'str'
Generate a URL to the given endpoint with the given values.
This requires an active request or application context, and calls
:meth:`current_app.url_for() <flask.Flask.url_for>`. See that method
for full documentation.
:param endpoint: The endpoint name associated with the URL to
generate. If this starts with a ``.``, the current blueprint
name (if any) will be used.
:param _anchor: If given, append this as ``#anchor`` to the URL.
:param _method: If given, generate the URL associated with this
method for the endpoint.
:param _scheme: If given, the URL will have this scheme if it is
external.
:param _external: If given, prefer the URL to be internal (False) or
require it to be external (True). External URLs include the
scheme and domain. When not in an active request, URLs are
external by default.
:param values: Values to use for the variable parts of the URL rule.
Unknown keys are appended as query string arguments, like
``?a=b&c=d``.
.. versionchanged:: 2.2
Calls ``current_app.url_for``, allowing an app to override the
behavior.
.. versionchanged:: 0.10
The ``_scheme`` parameter was added.
.. versionchanged:: 0.9
The ``_anchor`` and ``_method`` parameters were added.
.. versionchanged:: 0.9
Calls ``app.handle_url_build_error`` on build errors.
flask.wrappers
Python Library Documentation: module flask.wrappers in flask
NAME
flask.wrappers
CLASSES
werkzeug.wrappers.request.Request(werkzeug.sansio.request.Request)
Request
werkzeug.wrappers.response.Response(werkzeug.sansio.response.Response)
Response
class Request(werkzeug.wrappers.request.Request)
| Request(environ: 'WSGIEnvironment', populate_request: 'bool' = True, shallow: 'bool' = False) -> 'None'
|
| The request object used by default in Flask. Remembers the
| matched endpoint and view arguments.
|
| It is what ends up as :class:`~flask.request`. If you want to replace
| the request object used you can subclass this and set
| :attr:`~flask.Flask.request_class` to your subclass.
|
| The request object is a :class:`~werkzeug.wrappers.Request` subclass and
| provides all of the attributes Werkzeug defines plus a few Flask
| specific ones.
|
| Method resolution order:
| Request
| werkzeug.wrappers.request.Request
| werkzeug.sansio.request.Request
| builtins.object
|
| Methods defined here:
|
| on_json_loading_failed(self, e: 'ValueError | None') -> 't.Any'
| Called if :meth:`get_json` fails and isn't silenced.
|
| If this method returns a value, it is used as the return value
| for :meth:`get_json`. The default implementation raises
| :exc:`~werkzeug.exceptions.BadRequest`.
|
| :param e: If parsing failed, this is the exception. It will be
| ``None`` if the content type wasn't ``application/json``.
|
| .. versionchanged:: 2.3
| Raise a 415 error instead of 400.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| blueprint
| The registered name of the current blueprint.
|
| This will be ``None`` if the endpoint is not part of a
| blueprint, or if URL matching failed or has not been performed
| yet.
|
| This does not necessarily match the name the blueprint was
| created with. It may have been nested, or registered with a
| different name.
|
| blueprints
| The registered names of the current blueprint upwards through
| parent blueprints.
|
| This will be an empty list if there is no current blueprint, or
| if URL matching failed.
|
| .. versionadded:: 2.0.1
|
| endpoint
| The endpoint that matched the request URL.
|
| This will be ``None`` if matching failed or has not been
| performed yet.
|
| This in combination with :attr:`view_args` can be used to
| reconstruct the same URL or a modified URL.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| max_content_length
| The maximum number of bytes that will be read during this request. If
| this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge`
| error is raised. If it is set to ``None``, no limit is enforced at the
| Flask application level. However, if it is ``None`` and the request has
| no ``Content-Length`` header and the WSGI server does not indicate that
| it terminates the stream, then no data is read to avoid an infinite
| stream.
|
| Each request defaults to the :data:`MAX_CONTENT_LENGTH` config, which
| defaults to ``None``. It can be set on a specific ``request`` to apply
| the limit to that specific view. This should be set appropriately based
| on an application's or view's specific needs.
|
| .. versionchanged:: 3.1
| This can be set per-request.
|
| .. versionchanged:: 0.6
| This is configurable through Flask config.
|
| max_form_memory_size
| The maximum size in bytes any non-file form field may be in a
| ``multipart/form-data`` body. If this limit is exceeded, a 413
| :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it
| is set to ``None``, no limit is enforced at the Flask application level.
|
| Each request defaults to the :data:`MAX_FORM_MEMORY_SIZE` config, which
| defaults to ``500_000``. It can be set on a specific ``request`` to
| apply the limit to that specific view. This should be set appropriately
| based on an application's or view's specific needs.
|
| .. versionchanged:: 3.1
| This is configurable through Flask config.
|
| max_form_parts
| The maximum number of fields that may be present in a
| ``multipart/form-data`` body. If this limit is exceeded, a 413
| :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it
| is set to ``None``, no limit is enforced at the Flask application level.
|
| Each request defaults to the :data:`MAX_FORM_PARTS` config, which
| defaults to ``1_000``. It can be set on a specific ``request`` to apply
| the limit to that specific view. This should be set appropriately based
| on an application's or view's specific needs.
|
| .. versionchanged:: 3.1
| This is configurable through Flask config.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_max_content_length': 'int | None', '_max_form_mem...
|
| json_module = <module 'flask.json' from 'C:\\Users\\Youse\\App...2\\Li...
|
| routing_exception = None
|
| url_rule = None
|
| view_args = None
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.wrappers.request.Request:
|
| __enter__(self) -> 'Request'
|
| __exit__(self, exc_type, exc_value, tb) -> 'None'
|
| __init__(self, environ: 'WSGIEnvironment', populate_request: 'bool' = True, shallow: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| close(self) -> 'None'
| Closes associated resources of this request object. This
| closes all file handles explicitly. You can also use the request
| object in a with statement which will automatically close it.
|
| .. versionadded:: 0.9
|
| get_data(self, cache: 'bool' = True, as_text: 'bool' = False, parse_form_data: 'bool' = False) -> 'bytes | str'
| This reads the buffered incoming data from the client into one
| bytes object. By default this is cached but that behavior can be
| changed by setting `cache` to `False`.
|
| Usually it's a bad idea to call this method without checking the
| content length first as a client could send dozens of megabytes or more
| to cause memory problems on the server.
|
| Note that if the form data was already parsed this method will not
| return anything as form data parsing does not cache the data like
| this method does. To implicitly invoke form data parsing function
| set `parse_form_data` to `True`. When this is done the return value
| of this method will be an empty string if the form parser handles
| the data. This generally is not necessary as if the whole data is
| cached (which is the default) the form parser will used the cached
| data to parse the form data. Please be generally aware of checking
| the content length first in any case before calling this method
| to avoid exhausting server memory.
|
| If `as_text` is set to `True` the return value will be a decoded
| string.
|
| .. versionadded:: 0.9
|
| get_json(self, force: 'bool' = False, silent: 'bool' = False, cache: 'bool' = True) -> 't.Any | None'
| Parse :attr:`data` as JSON.
|
| If the mimetype does not indicate JSON
| (:mimetype:`application/json`, see :attr:`is_json`), or parsing
| fails, :meth:`on_json_loading_failed` is called and
| its return value is used as the return value. By default this
| raises a 415 Unsupported Media Type resp.
|
| :param force: Ignore the mimetype and always try to parse JSON.
| :param silent: Silence mimetype and parsing errors, and
| return ``None`` instead.
| :param cache: Store the parsed JSON to return for subsequent
| calls.
|
| .. versionchanged:: 2.3
| Raise a 415 error instead of 400.
|
| .. versionchanged:: 2.1
| Raise a 400 error if the content type is incorrect.
|
| make_form_data_parser(self) -> 'FormDataParser'
| Creates the form data parser. Instantiates the
| :attr:`form_data_parser_class` with some parameters.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Class methods inherited from werkzeug.wrappers.request.Request:
|
| application(f: 't.Callable[[Request], WSGIApplication]') -> 'WSGIApplication'
| Decorate a function as responder that accepts the request as
| the last argument. This works like the :func:`responder`
| decorator but the function is passed the request object as the
| last argument and the request object will be closed
| automatically::
|
| @Request.application
| def my_wsgi_app(request):
| return Response('Hello World!')
|
| As of Werkzeug 0.14 HTTP exceptions are automatically caught and
| converted to responses instead of failing.
|
| :param f: the WSGI callable to decorate
| :return: a new WSGI callable
|
| from_values(*args: 't.Any', **kwargs: 't.Any') -> 'Request'
| Create a new request object based on the values provided. If
| environ is given missing values are filled from there. This method is
| useful for small scripts when you need to simulate a request from an URL.
| Do not use this method for unittesting, there is a full featured client
| object (:class:`Client`) that allows to create multipart requests,
| support for cookies etc.
|
| This accepts the same options as the
| :class:`~werkzeug.test.EnvironBuilder`.
|
| .. versionchanged:: 0.5
| This method now accepts the same arguments as
| :class:`~werkzeug.test.EnvironBuilder`. Because of this the
| `environ` parameter is now called `environ_overrides`.
|
| :return: request object
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.wrappers.request.Request:
|
| data
| The raw data read from :attr:`stream`. Will be empty if the request
| represents form data.
|
| To get the raw data even if it represents form data, use :meth:`get_data`.
|
| files
| :class:`~werkzeug.datastructures.MultiDict` object containing
| all uploaded files. Each key in :attr:`files` is the name from the
| ``<input type="file" name="">``. Each value in :attr:`files` is a
| Werkzeug :class:`~werkzeug.datastructures.FileStorage` object.
|
| It basically behaves like a standard file object you know from Python,
| with the difference that it also has a
| :meth:`~werkzeug.datastructures.FileStorage.save` function that can
| store the file on the filesystem.
|
| Note that :attr:`files` will only contain data if the request method was
| POST, PUT or PATCH and the ``<form>`` that posted to the request had
| ``enctype="multipart/form-data"``. It will be empty otherwise.
|
| See the :class:`~werkzeug.datastructures.MultiDict` /
| :class:`~werkzeug.datastructures.FileStorage` documentation for
| more details about the used data structure.
|
| form
| The form parameters. By default an
| :class:`~werkzeug.datastructures.ImmutableMultiDict`
| is returned from this function. This can be changed by setting
| :attr:`parameter_storage_class` to a different type. This might
| be necessary if the order of the form data is important.
|
| Please keep in mind that file uploads will not end up here, but instead
| in the :attr:`files` attribute.
|
| .. versionchanged:: 0.9
|
| Previous to Werkzeug 0.9 this would only contain form data for POST
| and PUT requests.
|
| json
| The parsed JSON data if :attr:`mimetype` indicates JSON
| (:mimetype:`application/json`, see :attr:`is_json`).
|
| Calls :meth:`get_json` with default arguments.
|
| If the request content type is not ``application/json``, this
| will raise a 415 Unsupported Media Type error.
|
| .. versionchanged:: 2.3
| Raise a 415 error instead of 400.
|
| .. versionchanged:: 2.1
| Raise a 400 error if the content type is incorrect.
|
| script_root
| Alias for :attr:`self.root_path`. ``environ["SCRIPT_NAME"]``
| without a trailing slash.
|
| stream
| The WSGI input stream, with safety checks. This stream can only be consumed
| once.
|
| Use :meth:`get_data` to get the full data as bytes or text. The :attr:`data`
| attribute will contain the full bytes only if they do not represent form data.
| The :attr:`form` attribute will contain the parsed form data in that case.
|
| Unlike :attr:`input_stream`, this stream guards against infinite streams or
| reading past :attr:`content_length` or :attr:`max_content_length`.
|
| If ``max_content_length`` is set, it can be enforced on streams if
| ``wsgi.input_terminated`` is set. Otherwise, an empty stream is returned.
|
| If the limit is reached before the underlying stream is exhausted (such as a
| file that is too large, or an infinite stream), the remaining contents of the
| stream cannot be read safely. Depending on how the server handles this, clients
| may show a "connection reset" failure instead of seeing the 413 response.
|
| .. versionchanged:: 2.3
| Check ``max_content_length`` preemptively and while reading.
|
| .. versionchanged:: 0.9
| The stream is always set (but may be consumed) even if form parsing was
| accessed first.
|
| url_root
| Alias for :attr:`root_url`. The URL with scheme, host, and
| root path. For example, ``https://example.com/app/``.
|
| values
| A :class:`werkzeug.datastructures.CombinedMultiDict` that
| combines :attr:`args` and :attr:`form`.
|
| For GET requests, only ``args`` are present, not ``form``.
|
| .. versionchanged:: 2.0
| For GET requests, only ``args`` are present, not ``form``.
|
| want_form_data_parsed
| ``True`` if the request method carries content. By default
| this is true if a ``Content-Type`` is sent.
|
| .. versionadded:: 0.8
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.wrappers.request.Request:
|
| input_stream
| The raw WSGI input stream, without any safety checks.
|
| This is dangerous to use. It does not guard against infinite streams or reading
| past :attr:`content_length` or :attr:`max_content_length`.
|
| Use :attr:`stream` instead.
|
| is_multiprocess
| boolean that is `True` if the application is served by a
| WSGI server that spawns multiple processes.
|
| is_multithread
| boolean that is `True` if the application is served by a
| multithreaded WSGI server.
|
| is_run_once
| boolean that is `True` if the application will be
| executed only once in a process lifetime. This is the case for
| CGI for example, but it's not guaranteed that the execution only
| happens one time.
|
| remote_user
| If the server supports user authentication, and the
| script is protected, this attribute contains the username the
| user has authenticated as.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.wrappers.request.Request:
|
| form_data_parser_class = <class 'werkzeug.formparser.FormDataParser'>
| This class implements parsing of form data for Werkzeug. By itself
| it can parse multipart and url encoded form data. It can be subclassed
| and extended but for most mimetypes it is a better idea to use the
| untouched stream and expose it as separate attributes on a request
| object.
|
| :param stream_factory: An optional callable that returns a new read and
| writeable file descriptor. This callable works
| the same as :meth:`Response._get_file_stream`.
| :param max_form_memory_size: the maximum number of bytes to be accepted for
| in-memory stored form data. If the data
| exceeds the value specified an
| :exc:`~exceptions.RequestEntityTooLarge`
| exception is raised.
| :param max_content_length: If this is provided and the transmitted data
| is longer than this value an
| :exc:`~exceptions.RequestEntityTooLarge`
| exception is raised.
| :param cls: an optional dict class to use. If this is not specified
| or `None` the default :class:`MultiDict` is used.
| :param silent: If set to False parsing errors will not be caught.
| :param max_form_parts: The maximum number of multipart parts to be parsed. If this
| is exceeded, a :exc:`~exceptions.RequestEntityTooLarge` exception is raised.
|
| .. versionchanged:: 3.0
| The ``charset`` and ``errors`` parameters were removed.
|
| .. versionchanged:: 3.0
| The ``parse_functions`` attribute and ``get_parse_func`` methods were removed.
|
| .. versionchanged:: 2.2.3
| Added the ``max_form_parts`` parameter.
|
| .. versionadded:: 0.8
|
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.sansio.request.Request:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.sansio.request.Request:
|
| accept_charsets
| List of charsets this client supports as
| :class:`~werkzeug.datastructures.CharsetAccept` object.
|
| accept_encodings
| List of encodings this client accepts. Encodings in a HTTP term
| are compression encodings such as gzip. For charsets have a look at
| :attr:`accept_charset`.
|
| accept_languages
| List of languages this client accepts as
| :class:`~werkzeug.datastructures.LanguageAccept` object.
|
| .. versionchanged 0.5
| In previous versions this was a regular
| :class:`~werkzeug.datastructures.Accept` object.
|
| accept_mimetypes
| List of mimetypes this client supports as
| :class:`~werkzeug.datastructures.MIMEAccept` object.
|
| access_route
| If a forwarded header exists this is a list of all ip addresses
| from the client ip to the last proxy server.
|
| args
| The parsed URL parameters (the part in the URL after the question
| mark).
|
| By default an
| :class:`~werkzeug.datastructures.ImmutableMultiDict`
| is returned from this function. This can be changed by setting
| :attr:`parameter_storage_class` to a different type. This might
| be necessary if the order of the form data is important.
|
| .. versionchanged:: 2.3
| Invalid bytes remain percent encoded.
|
| authorization
| The ``Authorization`` header parsed into an :class:`.Authorization` object.
| ``None`` if the header is not present.
|
| .. versionchanged:: 2.3
| :class:`Authorization` is no longer a ``dict``. The ``token`` attribute
| was added for auth schemes that use a token instead of parameters.
|
| base_url
| Like :attr:`url` but without the query string.
|
| cache_control
| A :class:`~werkzeug.datastructures.RequestCacheControl` object
| for the incoming cache control headers.
|
| content_length
| The Content-Length entity-header field indicates the size of the
| entity-body in bytes or, in the case of the HEAD method, the size of
| the entity-body that would have been sent had the request been a
| GET.
|
| cookies
| A :class:`dict` with the contents of all cookies transmitted with
| the request.
|
| full_path
| Requested path, including the query string.
|
| host
| The host name the request was made to, including the port if
| it's non-standard. Validated with :attr:`trusted_hosts`.
|
| See :func:`.get_host` for a detailed explanation.
|
| host_url
| The request URL scheme and host only.
|
| if_match
| An object containing all the etags in the `If-Match` header.
|
| :rtype: :class:`~werkzeug.datastructures.ETags`
|
| if_modified_since
| The parsed `If-Modified-Since` header as a datetime object.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| if_none_match
| An object containing all the etags in the `If-None-Match` header.
|
| :rtype: :class:`~werkzeug.datastructures.ETags`
|
| if_range
| The parsed ``If-Range`` header.
|
| .. versionchanged:: 2.0
| ``IfRange.date`` is timezone-aware.
|
| .. versionadded:: 0.7
|
| if_unmodified_since
| The parsed `If-Unmodified-Since` header as a datetime object.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| is_json
| Check if the mimetype indicates JSON data, either
| :mimetype:`application/json` or :mimetype:`application/*+json`.
|
| is_secure
| ``True`` if the request was made with a secure protocol
| (HTTPS or WSS).
|
| mimetype
| Like :attr:`content_type`, but without parameters (eg, without
| charset, type etc.) and always lowercase. For example if the content
| type is ``text/HTML; charset=utf-8`` the mimetype would be
| ``'text/html'``.
|
| mimetype_params
| The mimetype parameters as dict. For example if the content
| type is ``text/html; charset=utf-8`` the params would be
| ``{'charset': 'utf-8'}``.
|
| pragma
| The Pragma general-header field is used to include
| implementation-specific directives that might apply to any recipient
| along the request/response chain. All pragma directives specify
| optional behavior from the viewpoint of the protocol; however, some
| systems MAY require that behavior be consistent with the directives.
|
| range
| The parsed `Range` header.
|
| .. versionadded:: 0.7
|
| :rtype: :class:`~werkzeug.datastructures.Range`
|
| root_url
| The request URL scheme, host, and root path. This is the root
| that the application is accessed from.
|
| url
| The full request URL with the scheme, host, root path, path,
| and query string.
|
| user_agent
| The user agent. Use ``user_agent.string`` to get the header
| value. Set :attr:`user_agent_class` to a subclass of
| :class:`~werkzeug.user_agent.UserAgent` to provide parsing for
| the other properties or other extended data.
|
| .. versionchanged:: 2.1
| The built-in parser was removed. Set ``user_agent_class`` to a ``UserAgent``
| subclass to parse data from the string.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.sansio.request.Request:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| access_control_request_headers
| Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set :attr:`~CORSResponseMixin.access_control_allow_headers` on the response to indicate which headers are allowed.
|
| access_control_request_method
| Sent with a preflight request to indicate which method will be used for the cross origin request. Set :attr:`~CORSResponseMixin.access_control_allow_methods` on the response to indicate which methods are allowed.
|
| content_encoding
| The Content-Encoding entity-header field is used as a
| modifier to the media-type. When present, its value indicates
| what additional content codings have been applied to the
| entity-body, and thus what decoding mechanisms must be applied
| in order to obtain the media-type referenced by the Content-Type
| header field.
|
| .. versionadded:: 0.9
|
| content_md5
| The Content-MD5 entity-header field, as defined in
| RFC 1864, is an MD5 digest of the entity-body for the purpose of
| providing an end-to-end message integrity check (MIC) of the
| entity-body. (Note: a MIC is good for detecting accidental
| modification of the entity-body in transit, but is not proof
| against malicious attacks.)
|
| .. versionadded:: 0.9
|
| content_type
| The Content-Type entity-header field indicates the media
| type of the entity-body sent to the recipient or, in the case of
| the HEAD method, the media type that would have been sent had
| the request been a GET.
|
| date
| The Date general-header field represents the date and
| time at which the message was originated, having the same
| semantics as orig-date in RFC 822.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| max_forwards
| The Max-Forwards request-header field provides a
| mechanism with the TRACE and OPTIONS methods to limit the number
| of proxies or gateways that can forward the request to the next
| inbound server.
|
| origin
| The host that the request originated from. Set :attr:`~CORSResponseMixin.access_control_allow_origin` on the response to indicate which origins are allowed.
|
| referrer
| The Referer[sic] request-header field allows the client
| to specify, for the server's benefit, the address (URI) of the
| resource from which the Request-URI was obtained (the
| "referrer", although the header field is misspelled).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.sansio.request.Request:
|
| dict_storage_class = <class 'werkzeug.datastructures.structures.Immuta...
| An immutable :class:`MultiDict`.
|
| .. versionadded:: 0.5
|
|
| list_storage_class = <class 'werkzeug.datastructures.structures.Immuta...
| An immutable :class:`list`.
|
| .. versionadded:: 0.5
|
| :private:
|
|
| parameter_storage_class = <class 'werkzeug.datastructures.structures.I...
| An immutable :class:`MultiDict`.
|
| .. versionadded:: 0.5
|
|
| trusted_hosts = None
|
| user_agent_class = <class 'werkzeug.user_agent.UserAgent'>
| Represents a parsed user agent header value.
|
| The default implementation does no parsing, only the :attr:`string`
| attribute is set. A subclass may parse the string to set the
| common attributes or expose other information. Set
| :attr:`werkzeug.wrappers.Request.user_agent_class` to use a
| subclass.
|
| :param string: The header value to parse.
|
| .. versionadded:: 2.0
| This replaces the previous ``useragents`` module, but does not
| provide a built-in parser.
class Response(werkzeug.wrappers.response.Response)
| Response(response: 't.Iterable[bytes] | bytes | t.Iterable[str] | str | None' = None, status: 'int | str | HTTPStatus | None' = None, headers: 't.Mapping[str, str | t.Iterable[str]] | t.Iterable[tuple[str, str]] | None' = None, mimetype: 'str | None' = None, content_type: 'str | None' = None, direct_passthrough: 'bool' = False) -> 'None'
|
| The response object that is used by default in Flask. Works like the
| response object from Werkzeug but is set to have an HTML mimetype by
| default. Quite often you don't have to create this object yourself because
| :meth:`~flask.Flask.make_response` will take care of that for you.
|
| If you want to replace the response object used you can subclass this and
| set :attr:`~flask.Flask.response_class` to your subclass.
|
| .. versionchanged:: 1.0
| JSON support is added to the response, like the request. This is useful
| when testing to get the test client response data as JSON.
|
| .. versionchanged:: 1.0
|
| Added :attr:`max_cookie_size`.
|
| Method resolution order:
| Response
| werkzeug.wrappers.response.Response
| werkzeug.sansio.response.Response
| builtins.object
|
| Readonly properties defined here:
|
| max_cookie_size
| Read-only view of the :data:`MAX_COOKIE_SIZE` config key.
|
| See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in
| Werkzeug's docs.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'default_mimetype': 'str | None'}
|
| autocorrect_location_header = False
|
| default_mimetype = 'text/html'
|
| json_module = <module 'flask.json' from 'C:\\Users\\Youse\\App...2\\Li...
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.wrappers.response.Response:
|
| __call__(self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 't.Iterable[bytes]'
| Process this response as WSGI application.
|
| :param environ: the WSGI environment.
| :param start_response: the response callable provided by the WSGI
| server.
| :return: an application iterator
|
| __enter__(self) -> 'Response'
|
| __exit__(self, exc_type, exc_value, tb)
|
| __init__(self, response: 't.Iterable[bytes] | bytes | t.Iterable[str] | str | None' = None, status: 'int | str | HTTPStatus | None' = None, headers: 't.Mapping[str, str | t.Iterable[str]] | t.Iterable[tuple[str, str]] | None' = None, mimetype: 'str | None' = None, content_type: 'str | None' = None, direct_passthrough: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_etag(self, overwrite: 'bool' = False, weak: 'bool' = False) -> 'None'
| Add an etag for the current response if there is none yet.
|
| .. versionchanged:: 2.0
| SHA-1 is used to generate the value. MD5 may not be
| available in some environments.
|
| calculate_content_length(self) -> 'int | None'
| Returns the content length if available or `None` otherwise.
|
| call_on_close(self, func: 't.Callable[[], t.Any]') -> 't.Callable[[], t.Any]'
| Adds a function to the internal list of functions that should
| be called as part of closing down the response. Since 0.7 this
| function also returns the function that was passed so that this
| can be used as a decorator.
|
| .. versionadded:: 0.6
|
| close(self) -> 'None'
| Close the wrapped response if possible. You can also use the object
| in a with statement which will automatically close it.
|
| .. versionadded:: 0.9
| Can now be used in a with statement.
|
| freeze(self) -> 'None'
| Make the response object ready to be pickled. Does the
| following:
|
| * Buffer the response into a list, ignoring
| :attr:`implicity_sequence_conversion` and
| :attr:`direct_passthrough`.
| * Set the ``Content-Length`` header.
| * Generate an ``ETag`` header if one is not already set.
|
| .. versionchanged:: 2.1
| Removed the ``no_etag`` parameter.
|
| .. versionchanged:: 2.0
| An ``ETag`` header is always added.
|
| .. versionchanged:: 0.6
| The ``Content-Length`` header is set.
|
| get_app_iter(self, environ: 'WSGIEnvironment') -> 't.Iterable[bytes]'
| Returns the application iterator for the given environ. Depending
| on the request method and the current status code the return value
| might be an empty response rather than the one from the response.
|
| If the request method is `HEAD` or the status code is in a range
| where the HTTP specification requires an empty response, an empty
| iterable is returned.
|
| .. versionadded:: 0.6
|
| :param environ: the WSGI environment of the request.
| :return: a response iterable.
|
| get_data(self, as_text: 'bool' = False) -> 'bytes | str'
| The string representation of the response body. Whenever you call
| this property the response iterable is encoded and flattened. This
| can lead to unwanted behavior if you stream big data.
|
| This behavior can be disabled by setting
| :attr:`implicit_sequence_conversion` to `False`.
|
| If `as_text` is set to `True` the return value will be a decoded
| string.
|
| .. versionadded:: 0.9
|
| get_json(self, force: 'bool' = False, silent: 'bool' = False) -> 't.Any | None'
| Parse :attr:`data` as JSON. Useful during testing.
|
| If the mimetype does not indicate JSON
| (:mimetype:`application/json`, see :attr:`is_json`), this
| returns ``None``.
|
| Unlike :meth:`Request.get_json`, the result is not cached.
|
| :param force: Ignore the mimetype and always try to parse JSON.
| :param silent: Silence parsing errors and return ``None``
| instead.
|
| get_wsgi_headers(self, environ: 'WSGIEnvironment') -> 'Headers'
| This is automatically called right before the response is started
| and returns headers modified for the given environment. It returns a
| copy of the headers from the response with some modifications applied
| if necessary.
|
| For example the location header (if present) is joined with the root
| URL of the environment. Also the content length is automatically set
| to zero here for certain status codes.
|
| .. versionchanged:: 0.6
| Previously that function was called `fix_headers` and modified
| the response object in place. Also since 0.6, IRIs in location
| and content-location headers are handled properly.
|
| Also starting with 0.6, Werkzeug will attempt to set the content
| length if it is able to figure it out on its own. This is the
| case if all the strings in the response iterable are already
| encoded and the iterable is buffered.
|
| :param environ: the WSGI environment of the request.
| :return: returns a new :class:`~werkzeug.datastructures.Headers`
| object.
|
| get_wsgi_response(self, environ: 'WSGIEnvironment') -> 'tuple[t.Iterable[bytes], str, list[tuple[str, str]]]'
| Returns the final WSGI response as tuple. The first item in
| the tuple is the application iterator, the second the status and
| the third the list of headers. The response returned is created
| specially for the given environment. For example if the request
| method in the WSGI environment is ``'HEAD'`` the response will
| be empty and only the headers and status code will be present.
|
| .. versionadded:: 0.6
|
| :param environ: the WSGI environment of the request.
| :return: an ``(app_iter, status, headers)`` tuple.
|
| iter_encoded(self) -> 't.Iterator[bytes]'
| Iter the response encoded with the encoding of the response.
| If the response object is invoked as WSGI application the return
| value of this method is used as application iterator unless
| :attr:`direct_passthrough` was activated.
|
| make_conditional(self, request_or_environ: 'WSGIEnvironment | Request', accept_ranges: 'bool | str' = False, complete_length: 'int | None' = None) -> 'Response'
| Make the response conditional to the request. This method works
| best if an etag was defined for the response already. The `add_etag`
| method can be used to do that. If called without etag just the date
| header is set.
|
| This does nothing if the request method in the request or environ is
| anything but GET or HEAD.
|
| For optimal performance when handling range requests, it's recommended
| that your response data object implements `seekable`, `seek` and `tell`
| methods as described by :py:class:`io.IOBase`. Objects returned by
| :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.
|
| It does not remove the body of the response because that's something
| the :meth:`__call__` function does for us automatically.
|
| Returns self so that you can do ``return resp.make_conditional(req)``
| but modifies the object in-place.
|
| :param request_or_environ: a request object or WSGI environment to be
| used to make the response conditional
| against.
| :param accept_ranges: This parameter dictates the value of
| `Accept-Ranges` header. If ``False`` (default),
| the header is not set. If ``True``, it will be set
| to ``"bytes"``. If it's a string, it will use this
| value.
| :param complete_length: Will be used only in valid Range Requests.
| It will set `Content-Range` complete length
| value and compute `Content-Length` real value.
| This parameter is mandatory for successful
| Range Requests completion.
| :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
| if `Range` header could not be parsed or satisfied.
|
| .. versionchangedd: 3.2
| Adds the ``Accept-Ranges`` header if ``accept_ranges`` is passed,
| even if this is not a satisfiable range request.
|
| .. versionchanged:: 2.0
| Range processing is skipped if length is 0 instead of
| raising a 416 Range Not Satisfiable error.
|
| make_sequence(self) -> 'None'
| Converts the response iterator in a list. By default this happens
| automatically if required. If `implicit_sequence_conversion` is
| disabled, this method is not automatically called and some properties
| might raise exceptions. This also encodes all the items.
|
| .. versionadded:: 0.6
|
| set_data(self, value: 'bytes | str') -> 'None'
| Sets a new string as response. The value must be a string or
| bytes. If a string is set it's encoded to the charset of the
| response (utf-8 by default).
|
| .. versionadded:: 0.9
|
| ----------------------------------------------------------------------
| Class methods inherited from werkzeug.wrappers.response.Response:
|
| force_type(response: 'Response', environ: 'WSGIEnvironment | None' = None) -> 'Response'
| Enforce that the WSGI response is a response object of the current
| type. Werkzeug will use the :class:`Response` internally in many
| situations like the exceptions. If you call :meth:`get_response` on an
| exception you will get back a regular :class:`Response` object, even
| if you are using a custom subclass.
|
| This method can enforce a given response type, and it will also
| convert arbitrary WSGI callables into response objects if an environ
| is provided::
|
| # convert a Werkzeug response object into an instance of the
| # MyResponseClass subclass.
| response = MyResponseClass.force_type(response)
|
| # convert any WSGI application into a response object
| response = MyResponseClass.force_type(response, environ)
|
| This is especially useful if you want to post-process responses in
| the main dispatcher and use functionality provided by your subclass.
|
| Keep in mind that this will modify response objects in place if
| possible!
|
| :param response: a response object or wsgi application.
| :param environ: a WSGI environment object.
| :return: a response object.
|
| from_app(app: 'WSGIApplication', environ: 'WSGIEnvironment', buffered: 'bool' = False) -> 'Response'
| Create a new response object from an application output. This
| works best if you pass it an application that returns a generator all
| the time. Sometimes applications may use the `write()` callable
| returned by the `start_response` function. This tries to resolve such
| edge cases automatically. But if you don't get the expected output
| you should set `buffered` to `True` which enforces buffering.
|
| :param app: the WSGI application to execute.
| :param environ: the WSGI environment to execute against.
| :param buffered: set to `True` to enforce buffering.
| :return: a response object.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.wrappers.response.Response:
|
| is_sequence
| If the iterator is buffered, this property will be `True`. A
| response object will consider an iterator to be buffered if the
| response attribute is a list or tuple.
|
| .. versionadded:: 0.6
|
| is_streamed
| If the response is streamed (the response is not an iterable with
| a length information) this property is `True`. In this case streamed
| means that there is no information about the number of iterations.
| This is usually `True` if a generator is passed to the response object.
|
| This is useful for checking before applying some sort of post
| filtering that should not take place for streamed responses.
|
| json
| The parsed JSON data if :attr:`mimetype` indicates JSON
| (:mimetype:`application/json`, see :attr:`is_json`).
|
| Calls :meth:`get_json` with default arguments.
|
| stream
| The response iterable as write-only stream.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.wrappers.response.Response:
|
| data
| A descriptor that calls :meth:`get_data` and :meth:`set_data`.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.wrappers.response.Response:
|
| automatically_set_content_length = True
|
| implicit_sequence_conversion = True
|
| ----------------------------------------------------------------------
| Methods inherited from werkzeug.sansio.response.Response:
|
| delete_cookie(self, key: 'str', path: 'str | None' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: 'str | None' = None, partitioned: 'bool' = False) -> 'None'
| Delete a cookie. Fails silently if key doesn't exist.
|
| :param key: the key (name) of the cookie to be deleted.
| :param path: if the cookie that should be deleted was limited to a
| path, the path has to be defined here.
| :param domain: if the cookie that should be deleted was limited to a
| domain, that domain has to be defined here.
| :param secure: If ``True``, the cookie will only be available
| via HTTPS.
| :param httponly: Disallow JavaScript access to the cookie.
| :param samesite: Limit the scope of the cookie to only be
| attached to requests that are "same-site".
| :param partitioned: If ``True``, the cookie will be partitioned.
|
| get_etag(self) -> 'tuple[str, bool] | tuple[None, None]'
| Return a tuple in the form ``(etag, is_weak)``. If there is no
| ETag the return value is ``(None, None)``.
|
| set_cookie(self, key: 'str', value: 'str' = '', max_age: 'timedelta | int | None' = None, expires: 'str | datetime | int | float | None' = None, path: 'str | None' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: 'str | None' = None, partitioned: 'bool' = False) -> 'None'
| Sets a cookie.
|
| A warning is raised if the size of the cookie header exceeds
| :attr:`max_cookie_size`, but the header will still be set.
|
| :param key: the key (name) of the cookie to be set.
| :param value: the value of the cookie.
| :param max_age: should be a number of seconds, or `None` (default) if
| the cookie should last only as long as the client's
| browser session.
| :param expires: should be a `datetime` object or UNIX timestamp.
| :param path: limits the cookie to a given path, per default it will
| span the whole domain.
| :param domain: if you want to set a cross-domain cookie. For example,
| ``domain="example.com"`` will set a cookie that is
| readable by the domain ``www.example.com``,
| ``foo.example.com`` etc. Otherwise, a cookie will only
| be readable by the domain that set it.
| :param secure: If ``True``, the cookie will only be available
| via HTTPS.
| :param httponly: Disallow JavaScript access to the cookie.
| :param samesite: Limit the scope of the cookie to only be
| attached to requests that are "same-site".
| :param partitioned: If ``True``, the cookie will be partitioned.
|
| .. versionchanged:: 3.1
| The ``partitioned`` parameter was added.
|
| set_etag(self, etag: 'str', weak: 'bool' = False) -> 'None'
| Set the etag, and override the old one if there was one.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from werkzeug.sansio.response.Response:
|
| cache_control
| The Cache-Control general-header field is used to specify
| directives that MUST be obeyed by all caching mechanisms along the
| request/response chain.
|
| is_json
| Check if the mimetype indicates JSON data, either
| :mimetype:`application/json` or :mimetype:`application/*+json`.
|
| mimetype_params
| The mimetype parameters as dict. For example if the
| content type is ``text/html; charset=utf-8`` the params would be
| ``{'charset': 'utf-8'}``.
|
| .. versionadded:: 0.5
|
| ----------------------------------------------------------------------
| Data descriptors inherited from werkzeug.sansio.response.Response:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| accept_ranges
| The `Accept-Ranges` header. Even though the name would
| indicate that multiple values are supported, it must be one
| string token only.
|
| The values ``'bytes'`` and ``'none'`` are common.
|
| .. versionadded:: 0.7
|
| access_control_allow_credentials
| Whether credentials can be shared by the browser to
| JavaScript code. As part of the preflight request it indicates
| whether credentials can be used on the cross origin request.
|
| access_control_allow_headers
| Which headers can be sent with the cross origin request.
|
| access_control_allow_methods
| Which methods can be used for the cross origin request.
|
| access_control_allow_origin
| The origin or '*' for any origin that may make cross origin requests.
|
| access_control_expose_headers
| Which headers can be shared by the browser to JavaScript code.
|
| access_control_max_age
| The maximum age in seconds the access control settings can be cached for.
|
| age
| The Age response-header field conveys the sender's
| estimate of the amount of time since the response (or its
| revalidation) was generated at the origin server.
|
| Age values are non-negative decimal integers, representing time
| in seconds.
|
| allow
| The Allow entity-header field lists the set of methods
| supported by the resource identified by the Request-URI. The
| purpose of this field is strictly to inform the recipient of
| valid methods associated with the resource. An Allow header
| field MUST be present in a 405 (Method Not Allowed)
| response.
|
| content_encoding
| The Content-Encoding entity-header field is used as a
| modifier to the media-type. When present, its value indicates
| what additional content codings have been applied to the
| entity-body, and thus what decoding mechanisms must be applied
| in order to obtain the media-type referenced by the Content-Type
| header field.
|
| content_language
| The Content-Language entity-header field describes the
| natural language(s) of the intended audience for the enclosed
| entity. Note that this might not be equivalent to all the
| languages used within the entity-body.
|
| content_length
| The Content-Length entity-header field indicates the size
| of the entity-body, in decimal number of OCTETs, sent to the
| recipient or, in the case of the HEAD method, the size of the
| entity-body that would have been sent had the request been a
| GET.
|
| content_location
| The Content-Location entity-header field MAY be used to
| supply the resource location for the entity enclosed in the
| message when that entity is accessible from a location separate
| from the requested resource's URI.
|
| content_md5
| The Content-MD5 entity-header field, as defined in
| RFC 1864, is an MD5 digest of the entity-body for the purpose of
| providing an end-to-end message integrity check (MIC) of the
| entity-body. (Note: a MIC is good for detecting accidental
| modification of the entity-body in transit, but is not proof
| against malicious attacks.)
|
| content_range
| The ``Content-Range`` header as a
| :class:`~werkzeug.datastructures.ContentRange` object. Available
| even if the header is not set.
|
| .. versionadded:: 0.7
|
| content_security_policy
| The ``Content-Security-Policy`` header as a
| :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
| even if the header is not set.
|
| The Content-Security-Policy header adds an additional layer of
| security to help detect and mitigate certain types of attacks.
|
| content_security_policy_report_only
| The ``Content-Security-policy-report-only`` header as a
| :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
| even if the header is not set.
|
| The Content-Security-Policy-Report-Only header adds a csp policy
| that is not enforced but is reported thereby helping detect
| certain types of attacks.
|
| content_type
| The Content-Type entity-header field indicates the media
| type of the entity-body sent to the recipient or, in the case of
| the HEAD method, the media type that would have been sent had
| the request been a GET.
|
| cross_origin_embedder_policy
| Prevents a document from loading any cross-origin resources that do not
| explicitly grant the document permission. Values must be a member of the
| :class:`werkzeug.http.COEP` enum.
|
| cross_origin_opener_policy
| Allows control over sharing of browsing context group with cross-origin
| documents. Values must be a member of the :class:`werkzeug.http.COOP` enum.
|
| date
| The Date general-header field represents the date and
| time at which the message was originated, having the same
| semantics as orig-date in RFC 822.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| expires
| The Expires entity-header field gives the date/time after
| which the response is considered stale. A stale cache entry may
| not normally be returned by a cache.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| last_modified
| The Last-Modified entity-header field indicates the date
| and time at which the origin server believes the variant was
| last modified.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| location
| The Location response-header field is used to redirect
| the recipient to a location other than the Request-URI for
| completion of the request or identification of a new
| resource.
|
| mimetype
| The mimetype (content type without charset etc.)
|
| retry_after
| The Retry-After response-header field can be used with a
| 503 (Service Unavailable) response to indicate how long the
| service is expected to be unavailable to the requesting client.
|
| Time in seconds until expiration or date.
|
| .. versionchanged:: 2.0
| The datetime object is timezone-aware.
|
| status
| The HTTP status code as a string.
|
| status_code
| The HTTP status code as a number.
|
| vary
| The Vary field value indicates the set of request-header
| fields that fully determines, while the response is fresh,
| whether a cache is permitted to use the response to reply to a
| subsequent request without revalidation.
|
| www_authenticate
| The ``WWW-Authenticate`` header parsed into a :class:`.WWWAuthenticate`
| object. Modifying the object will modify the header value.
|
| This header is not set by default. To set this header, assign an instance of
| :class:`.WWWAuthenticate` to this attribute.
|
| .. code-block:: python
|
| response.www_authenticate = WWWAuthenticate(
| "basic", {"realm": "Authentication Required"}
| )
|
| Multiple values for this header can be sent to give the client multiple options.
| Assign a list to set multiple headers. However, modifying the items in the list
| will not automatically update the header values, and accessing this attribute
| will only ever return the first value.
|
| To unset this header, assign ``None`` or use ``del``.
|
| .. versionchanged:: 2.3
| This attribute can be assigned to set the header. A list can be assigned
| to set multiple header values. Use ``del`` to unset the header.
|
| .. versionchanged:: 2.3
| :class:`WWWAuthenticate` is no longer a ``dict``. The ``token`` attribute
| was added for auth challenges that use a token instead of parameters.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from werkzeug.sansio.response.Response:
|
| default_status = 200
DATA
current_app = <LocalProxy unbound>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\flask\wrappers.py