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 :

Vous êtes un professionnel et vous avez besoin d'une formation ? Coder avec une
Intelligence Artificielle
Voir le programme détaillé
Module « flask »

Classe « Flask »

Informations générales

Héritage

builtins.object
    Scaffold
        App
            Flask

Définition

class Flask(App):

help(Flask)

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: '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)

Liste des attributs statiques

Nom de l'attribut Valeur
default_configImmutableDict({'DEBUG': None, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SECRET_KEY_FALLBACKS': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'TRUSTED_HOSTS': None, '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_PARTITIONED': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'MAX_FORM_MEMORY_SIZE': 500000, 'MAX_FORM_PARTS': 1000, 'SEND_FILE_MAX_AGE_DEFAULT': None, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'PROVIDE_AUTOMATIC_OPTIONS': True})
jinja_options{}
permanent_session_lifetime<flask.config.ConfigAttribute object at 0x0000020D9EE81090>
secret_key<flask.config.ConfigAttribute object at 0x0000020D9EE81310>
session_interface<flask.sessions.SecureCookieSessionInterface object at 0x0000020D9F150050>
test_cli_runner_classNone
test_client_classNone
testing<flask.config.ConfigAttribute object at 0x0000020D9ED0AA50>

Liste des propriétés

Nom de la propriétéDescription
debugWhether debug mode is enabled. When using ``flask run`` to start the [extrait de debug.__doc__]
has_static_folder``True`` if :attr:`static_folder` is set. [extrait de has_static_folder.__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__]
static_folderThe absolute path to the configured static folder. ``None`` [extrait de static_folder.__doc__]
static_url_pathThe URL prefix that the static route will be accessible from. [extrait de static_url_path.__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: 'WSGIEnvironment', start_response: 'StartResponse') -> 'cabc.Iterable[bytes]' The WSGI server calls the Flask application object as the [extrait de __call__.__doc__]
app_context(self) -> 'AppContext' Create an :class:`~flask.ctx.AppContext`. Use as a ``with`` [extrait de app_context.__doc__]
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. [extrait de async_to_sync.__doc__]
create_jinja_environment(self) -> 'Environment' Create the Jinja environment based on :attr:`jinja_options` [extrait de create_jinja_environment.__doc__]
create_url_adapter(self, request: 'Request | None') -> 'MapAdapter | None' Creates a URL adapter for the given request. The URL adapter [extrait de create_url_adapter.__doc__]
dispatch_request(self) -> 'ft.ResponseReturnValue' Does the request dispatching. Matches the URL and returns the [extrait de dispatch_request.__doc__]
do_teardown_appcontext(self, exc: 'BaseException | None' = <object object at 0x0000020D9A572540>) -> 'None' Called right before the application context is popped. [extrait de do_teardown_appcontext.__doc__]
do_teardown_request(self, exc: 'BaseException | None' = <object object at 0x0000020D9A572540>) -> 'None' Called after the request is dispatched and the response is [extrait de do_teardown_request.__doc__]
ensure_sync(self, func: 't.Callable[..., t.Any]') -> 't.Callable[..., t.Any]' Ensure that the function is synchronous for WSGI workers. [extrait de ensure_sync.__doc__]
finalize_request(self, rv: 'ft.ResponseReturnValue | HTTPException', from_error_handler: 'bool' = False) -> 'Response' Given the return value from a view function this finalizes [extrait de finalize_request.__doc__]
full_dispatch_request(self) -> 'Response' Dispatches the request and on top of that performs request [extrait de full_dispatch_request.__doc__]
get_send_file_max_age(self, filename: 'str | None') -> 'int | None' Used by :func:`send_file` to determine the ``max_age`` cache [extrait de get_send_file_max_age.__doc__]
handle_exception(self, e: 'Exception') -> 'Response' Handle an exception that did not have an error handler [extrait de handle_exception.__doc__]
handle_http_exception(self, e: 'HTTPException') -> 'HTTPException | ft.ResponseReturnValue' Handles an HTTP exception. By default this will invoke the [extrait de handle_http_exception.__doc__]
handle_user_exception(self, e: 'Exception') -> 'HTTPException | ft.ResponseReturnValue' This method is called whenever an exception occurs that [extrait de handle_user_exception.__doc__]
log_exception(self, exc_info: 'tuple[type, BaseException, TracebackType] | tuple[None, None, None]') -> 'None' Logs an exception. This is called by :meth:`handle_exception` [extrait de log_exception.__doc__]
make_default_options_response(self) -> 'Response' This method is called to create the default ``OPTIONS`` response. [extrait de make_default_options_response.__doc__]
make_response(self, rv: 'ft.ResponseReturnValue') -> 'Response' Convert the return value from a view function to an instance of [extrait de make_response.__doc__]
make_shell_context(self) -> 'dict[str, t.Any]' 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', encoding: 'str | None' = 'utf-8') -> 't.IO[t.AnyStr]' Open a resource file relative to the application's instance folder [extrait de open_instance_resource.__doc__]
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. [extrait de open_resource.__doc__]
preprocess_request(self) -> 'ft.ResponseReturnValue | None' Called before the request is dispatched. Calls [extrait de preprocess_request.__doc__]
process_response(self, response: 'Response') -> 'Response' Can be overridden in order to modify the response object [extrait de process_response.__doc__]
raise_routing_exception(self, request: 'Request') -> 't.NoReturn' Intercept routing exceptions and possibly do something else. [extrait de raise_routing_exception.__doc__]
request_context(self, environ: 'WSGIEnvironment') -> 'RequestContext' Create a :class:`~flask.ctx.RequestContext` representing a [extrait de request_context.__doc__]
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. [extrait de run.__doc__]
send_static_file(self, filename: 'str') -> 'Response' The view function used to serve files from [extrait de send_static_file.__doc__]
test_cli_runner(self, **kwargs: 't.Any') -> 'FlaskCliRunner' Create a CLI runner for testing CLI commands. [extrait de test_cli_runner.__doc__]
test_client(self, use_cookies: 'bool' = True, **kwargs: 't.Any') -> 'FlaskClient' Creates a test client for this application. For information [extrait de test_client.__doc__]
test_request_context(self, *args: 't.Any', **kwargs: 't.Any') -> 'RequestContext' Create a :class:`~flask.ctx.RequestContext` for a WSGI [extrait de test_request_context.__doc__]
update_template_context(self, context: 'dict[str, t.Any]') -> 'None' Update the template context with some commonly used variables. [extrait de update_template_context.__doc__]
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. [extrait de url_for.__doc__]
wsgi_app(self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 'cabc.Iterable[bytes]' The actual WSGI application. This is not implemented in [extrait de wsgi_app.__doc__]

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

__init_subclass__, __subclasshook__, add_template_filter, add_template_global, add_template_test, add_url_rule, auto_find_instance_path, create_global_jinja_loader, handle_url_build_error, inject_url_defaults, iter_blueprints, make_aborter, make_config, redirect, register_blueprint, select_jinja_autoescape, shell_context_processor, should_ignore_error, teardown_appcontext, template_filter, template_global, template_test, trap_http_exception

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

__repr__, after_request, before_request, context_processor, delete, endpoint, errorhandler, get, patch, post, put, register_error_handler, route, teardown_request, url_defaults, url_value_preprocessor

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

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

Vous êtes un professionnel et vous avez besoin d'une formation ? Programmation Python
Les compléments
Voir le programme détaillé