Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Module « flask »

Classe « Flask »

Informations générales

Héritage

builtins.object
    Scaffold
        Flask

Définition

class Flask(Scaffold):

Description [extrait de Flask.__doc__]

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.
    

Constructeur(s)

Signature du constructeur Description
__init__(self, import_name: str, static_url_path: Optional[str] = None, static_folder: Union[str, os.PathLike, NoneType] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', instance_path: Optional[str] = None, instance_relative_config: bool = False, root_path: Optional[str] = None)

Liste des attributs statiques

Nom de l'attribut Valeur
default_configImmutableDict({'ENV': None, 'DEBUG': None, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': None, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093})
env<flask.config.ConfigAttribute object at 0x7f40cbf27c10>
jinja_options{}
permanent_session_lifetime<flask.config.ConfigAttribute object at 0x7f40cbf27850>
secret_key<flask.config.ConfigAttribute object at 0x7f40cbf27790>
send_file_max_age_default<flask.config.ConfigAttribute object at 0x7f40cbf278b0>
session_cookie_name<flask.config.ConfigAttribute object at 0x7f40cbf277f0>
session_interface<flask.sessions.SecureCookieSessionInterface object at 0x7f40cbf279a0>
test_cli_runner_classNone
test_client_classNone
testing<flask.config.ConfigAttribute object at 0x7f40cc038910>
use_x_sendfile<flask.config.ConfigAttribute object at 0x7f40cbf27910>

Attributs statiques hérités de la classe Scaffold

json_decoder, json_encoder

Liste des propriétés

Nom de la propriétéDescription
debugWhether debug mode is enabled. When using ``flask run`` to start [extrait de __doc__]
got_first_requestThis attribute is set to ``True`` if the application started [extrait de __doc__]
has_static_folder``True`` if :attr:`static_folder` is set. [extrait de __doc__]
jinja_envThe Jinja environment used to load templates. [extrait de jinja_env.__doc__]
jinja_loaderThe Jinja loader for this object's templates. By default this [extrait de jinja_loader.__doc__]
loggerA standard Python :class:`~logging.Logger` for the app, with [extrait de logger.__doc__]
nameThe name of the application. This is usually the import name [extrait de name.__doc__]
preserve_context_on_exceptionReturns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION`` [extrait de __doc__]
propagate_exceptionsReturns the value of the ``PROPAGATE_EXCEPTIONS`` configuration [extrait de __doc__]
static_folderThe absolute path to the configured static folder. ``None`` [extrait de __doc__]
static_url_pathThe URL prefix that the static route will be accessible from. [extrait de __doc__]
templates_auto_reloadReload templates when they are changed. Used by [extrait de __doc__]

Liste des opérateurs

Opérateurs hérités de la classe object

__eq__, __ge__, __gt__, __le__, __lt__, __ne__

Liste des méthodes

Toutes les méthodes Méthodes d'instance Méthodes statiques Méthodes dépréciées
Signature de la méthodeDescription
__call__(self, environ: dict, start_response: Callable) -> Any The WSGI server calls the Flask application object as the [extrait de __call__.__doc__]
add_template_filter(self, f: Callable[..., Any], name: Optional[str] = None) -> None Register a custom template filter. Works exactly like the [extrait de add_template_filter.__doc__]
add_template_global(self, f: Callable[..., Any], name: Optional[str] = None) -> None Register a custom template global function. Works exactly like the [extrait de add_template_global.__doc__]
add_template_test(self, f: Callable[..., bool], name: Optional[str] = None) -> None Register a custom template test. Works exactly like the [extrait de add_template_test.__doc__]
add_url_rule(self, rule: str, endpoint: Optional[str] = None, view_func: Optional[Callable] = None, provide_automatic_options: Optional[bool] = None, **options: Any) -> None
app_context(self) -> flask.ctx.AppContext Create an :class:`~flask.ctx.AppContext`. Use as a ``with`` [extrait de app_context.__doc__]
async_to_sync(self, func: Callable[..., Coroutine]) -> Callable[..., Any] Return a sync function that will run the coroutine function. [extrait de async_to_sync.__doc__]
auto_find_instance_path(self) -> str Tries to locate the instance path if it was not provided to the [extrait de auto_find_instance_path.__doc__]
before_first_request(self, f: Callable[[], NoneType]) -> Callable[[], NoneType] Registers a function to be run before the first request to this [extrait de before_first_request.__doc__]
create_global_jinja_loader(self) -> flask.templating.DispatchingJinjaLoader Creates the loader for the Jinja2 environment. Can be used to [extrait de create_global_jinja_loader.__doc__]
create_jinja_environment(self) -> flask.templating.Environment Create the Jinja environment based on :attr:`jinja_options` [extrait de create_jinja_environment.__doc__]
create_url_adapter(self, request: Optional[flask.wrappers.Request]) -> Optional[werkzeug.routing.MapAdapter] Creates a URL adapter for the given request. The URL adapter [extrait de create_url_adapter.__doc__]
dispatch_request(self) -> Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int, Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], ForwardRef('WSGIApplication')] Does the request dispatching. Matches the URL and returns the [extrait de dispatch_request.__doc__]
do_teardown_appcontext(self, exc: Optional[BaseException] = <object object at 0x7f40e98e2d50>) -> None Called right before the application context is popped. [extrait de do_teardown_appcontext.__doc__]
do_teardown_request(self, exc: Optional[BaseException] = <object object at 0x7f40e98e2d50>) -> None Called after the request is dispatched and the response is [extrait de do_teardown_request.__doc__]
ensure_sync(self, func: Callable) -> Callable Ensure that the function is synchronous for WSGI workers. [extrait de ensure_sync.__doc__]
finalize_request(self, rv: Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int, Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], ForwardRef('WSGIApplication'), werkzeug.exceptions.HTTPException], from_error_handler: bool = False) -> flask.wrappers.Response Given the return value from a view function this finalizes [extrait de finalize_request.__doc__]
full_dispatch_request(self) -> flask.wrappers.Response Dispatches the request and on top of that performs request [extrait de full_dispatch_request.__doc__]
handle_exception(self, e: Exception) -> flask.wrappers.Response Handle an exception that did not have an error handler [extrait de handle_exception.__doc__]
handle_http_exception(self, e: werkzeug.exceptions.HTTPException) -> Union[werkzeug.exceptions.HTTPException, ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int, Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], ForwardRef('WSGIApplication')] Handles an HTTP exception. By default this will invoke the [extrait de handle_http_exception.__doc__]
handle_url_build_error(self, error: Exception, endpoint: str, values: dict) -> str Handle :class:`~werkzeug.routing.BuildError` on [extrait de handle_url_build_error.__doc__]
handle_user_exception(self, e: Exception) -> Union[werkzeug.exceptions.HTTPException, ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int, Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], ForwardRef('WSGIApplication')] This method is called whenever an exception occurs that [extrait de handle_user_exception.__doc__]
inject_url_defaults(self, endpoint: str, values: dict) -> None Injects the URL defaults for the given endpoint directly into [extrait de inject_url_defaults.__doc__]
iter_blueprints(self) -> ValuesView[ForwardRef('Blueprint')] Iterates over all blueprints by the order they were registered. [extrait de iter_blueprints.__doc__]
log_exception(self, exc_info: Union[Tuple[type, BaseException, traceback], Tuple[NoneType, NoneType, NoneType]]) -> None Logs an exception. This is called by :meth:`handle_exception` [extrait de log_exception.__doc__]
make_config(self, instance_relative: bool = False) -> flask.config.Config Used to create the config attribute by the Flask constructor. [extrait de make_config.__doc__]
make_default_options_response(self) -> flask.wrappers.Response This method is called to create the default ``OPTIONS`` response. [extrait de make_default_options_response.__doc__]
make_response(self, rv: Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int, Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], ForwardRef('WSGIApplication')]) -> flask.wrappers.Response Convert the return value from a view function to an instance of [extrait de make_response.__doc__]
make_shell_context(self) -> dict Returns the shell context for an interactive shell for this [extrait de make_shell_context.__doc__]
open_instance_resource(self, resource: str, mode: str = 'rb') -> IO[~AnyStr] Opens a resource from the application's instance folder [extrait de open_instance_resource.__doc__]
preprocess_request(self) -> Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int], Tuple[Union[ForwardRef('Response'), ~AnyStr, Dict[str, Any], Generator[~AnyStr, NoneType, NoneType]], int, Union[ForwardRef('Headers'), Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], ForwardRef('WSGIApplication'), NoneType] Called before the request is dispatched. Calls [extrait de preprocess_request.__doc__]
process_response(self, response: flask.wrappers.Response) -> flask.wrappers.Response Can be overridden in order to modify the response object [extrait de process_response.__doc__]
raise_routing_exception(self, request: flask.wrappers.Request) -> 'te.NoReturn' Exceptions that are recording during routing are reraised with [extrait de raise_routing_exception.__doc__]
register_blueprint(self, blueprint: 'Blueprint', **options: Any) -> None Register a :class:`~flask.Blueprint` on the application. Keyword [extrait de register_blueprint.__doc__]
request_context(self, environ: dict) -> flask.ctx.RequestContext Create a :class:`~flask.ctx.RequestContext` representing a [extrait de request_context.__doc__]
run(self, host: Optional[str] = None, port: Optional[int] = None, debug: Optional[bool] = None, load_dotenv: bool = True, **options: Any) -> None Runs the application on a local development server. [extrait de run.__doc__]
select_jinja_autoescape(self, filename: str) -> bool Returns ``True`` if autoescaping should be active for the given [extrait de select_jinja_autoescape.__doc__]
shell_context_processor(self, f: Callable) -> Callable Registers a shell context processor function. [extrait de shell_context_processor.__doc__]
should_ignore_error(self, error: Optional[BaseException]) -> bool This is called to figure out if an error should be ignored [extrait de should_ignore_error.__doc__]
teardown_appcontext(self, f: Callable[[Optional[BaseException]], NoneType]) -> Callable[[Optional[BaseException]], NoneType] Registers a function to be called when the application context [extrait de teardown_appcontext.__doc__]
template_filter(self, name: Optional[str] = None) -> Callable[[Callable[..., Any]], Callable[..., Any]] A decorator that is used to register custom template filter. [extrait de template_filter.__doc__]
template_global(self, name: Optional[str] = None) -> Callable[[Callable[..., Any]], Callable[..., Any]] A decorator that is used to register a custom template global function. [extrait de template_global.__doc__]
template_test(self, name: Optional[str] = None) -> Callable[[Callable[..., bool]], Callable[..., bool]] A decorator that is used to register custom template test. [extrait de template_test.__doc__]
test_cli_runner(self, **kwargs: Any) -> 'FlaskCliRunner' Create a CLI runner for testing CLI commands. [extrait de test_cli_runner.__doc__]
test_client(self, use_cookies: bool = True, **kwargs: Any) -> 'FlaskClient' Creates a test client for this application. For information [extrait de test_client.__doc__]
test_request_context(self, *args: Any, **kwargs: Any) -> flask.ctx.RequestContext Create a :class:`~flask.ctx.RequestContext` for a WSGI [extrait de test_request_context.__doc__]
trap_http_exception(self, e: Exception) -> bool Checks if an HTTP exception should be trapped or not. By default [extrait de trap_http_exception.__doc__]
try_trigger_before_first_request_functions(self) -> None Called before each request and will ensure that it triggers [extrait de try_trigger_before_first_request_functions.__doc__]
update_template_context(self, context: dict) -> None Update the template context with some commonly used variables. [extrait de update_template_context.__doc__]
wsgi_app(self, environ: dict, start_response: Callable) -> Any The actual WSGI application. This is not implemented in [extrait de wsgi_app.__doc__]

Méthodes héritées de la classe Scaffold

__init_subclass__, __repr__, __subclasshook__, after_request, before_request, context_processor, delete, endpoint, errorhandler, get, get_send_file_max_age, open_resource, patch, post, put, register_error_handler, route, send_static_file, teardown_request, url_defaults, url_value_preprocessor

Méthodes héritées de la classe object

__delattr__, __dir__, __format__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __setattr__, __sizeof__, __str__