OpenQuizz
Une application de gestion des contenus pédagogiques
flask.helpers Namespace Reference

Data Structures

class  _PackageBoundObject
 
class  locked_cached_property
 

Functions

def get_env ()
 
def get_debug_flag ()
 
def get_load_dotenv (default=True)
 
def stream_with_context (generator_or_function)
 
def make_response (*args)
 
def url_for (endpoint, **values)
 
def get_template_attribute (template_name, attribute)
 
def flash (message, category="message")
 
def get_flashed_messages (with_categories=False, category_filter=())
 
def send_file (filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False, last_modified=None)
 
def safe_join (directory, *pathnames)
 
def send_from_directory (directory, filename, **options)
 
def get_root_path (import_name)
 
def find_package (import_name)
 
def total_seconds (td)
 
def is_ip (value)
 

Function Documentation

◆ find_package()

def flask.helpers.find_package (   import_name)
Finds a package and returns the prefix (or None if the package is
not installed) as well as the folder that contains the package or
module as a tuple.  The package path returned is the module that would
have to be added to the pythonpath in order to make it possible to
import the module.  The prefix is the path below which a UNIX like
folder structure exists (lib, share etc.).

◆ flash()

def flask.helpers.flash (   message,
  category = "message" 
)
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()

def flask.helpers.get_debug_flag ( )
Get whether debug mode should be enabled for the app, indicated
by the :envvar:`FLASK_DEBUG` environment variable. The default is
``True`` if :func:`.get_env` returns ``'development'``, or ``False``
otherwise.

◆ get_env()

def flask.helpers.get_env ( )
Get the environment the app is running in, indicated by the
:envvar:`FLASK_ENV` environment variable. The default is
``'production'``.

◆ get_flashed_messages()

def flask.helpers.get_flashed_messages (   with_categories = False,
  category_filter = () 
)
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 :ref:`message-flashing-pattern` 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: whitelist of categories to limit return values

◆ get_load_dotenv()

def flask.helpers.get_load_dotenv (   default = True)
Get whether the user has disabled loading 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()

def flask.helpers.get_root_path (   import_name)
Returns the path to a package or cwd if that cannot be found.  This
returns the path of a package or the folder that contains a module.

Not to be confused with the package path returned by :func:`find_package`.

◆ get_template_attribute()

def flask.helpers.get_template_attribute (   template_name,
  attribute 
)
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

◆ is_ip()

def flask.helpers.is_ip (   value)
Determine if the given string is an IP address.

Python 2 on Windows doesn't provide ``inet_pton``, so this only
checks IPv4 addresses in that environment.

:param value: value to check
:type value: str

:return: True if string is an IP address
:rtype: bool

◆ make_response()

def flask.helpers.make_response ( args)
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

◆ safe_join()

def flask.helpers.safe_join (   directory,
pathnames 
)
Safely join `directory` and zero or more untrusted `pathnames`
components.

Example usage::

    @app.route('/wiki/<path:filename>')
    def wiki_page(filename):
        filename = safe_join(app.config['WIKI_FOLDER'], filename)
        with open(filename, 'rb') as fd:
            content = fd.read()  # Read and process the file content...

:param directory: the trusted base directory.
:param pathnames: the untrusted pathnames relative to that directory.
:raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed
        paths fall out of its boundaries.

◆ send_file()

def flask.helpers.send_file (   filename_or_fp,
  mimetype = None,
  as_attachment = False,
  attachment_filename = None,
  add_etags = True,
  cache_timeout = None,
  conditional = False,
  last_modified = None 
)
Sends the contents of a file to the client.  This will use the
most efficient method available and configured.  By default it will
try to use the WSGI server's file_wrapper support.  Alternatively
you can set the application's :attr:`~Flask.use_x_sendfile` attribute
to ``True`` to directly emit an ``X-Sendfile`` header.  This however
requires support of the underlying webserver for ``X-Sendfile``.

By default it will try to guess the mimetype for you, but you can
also explicitly provide one.  For extra security you probably want
to send certain files as attachment (HTML for instance).  The mimetype
guessing requires a `filename` or an `attachment_filename` to be
provided.

ETags will also be attached automatically if a `filename` is provided. You
can turn this off by setting `add_etags=False`.

If `conditional=True` and `filename` is provided, this method will try to
upgrade the response stream to support range requests.  This will allow
the request to be answered with partial content response.

Please never pass filenames to this function from user sources;
you should use :func:`send_from_directory` instead.

.. versionadded:: 0.2

.. versionadded:: 0.5
   The `add_etags`, `cache_timeout` and `conditional` parameters were
   added.  The default behavior is now to attach etags.

.. versionchanged:: 0.7
   mimetype guessing and etag support for file objects was
   deprecated because it was unreliable.  Pass a filename if you are
   able to, otherwise attach an etag yourself.  This functionality
   will be removed in Flask 1.0

.. versionchanged:: 0.9
   cache_timeout pulls its default from application config, when None.

.. versionchanged:: 0.12
   The filename is no longer automatically inferred from file objects. If
   you want to use automatic mimetype and etag support, pass a filepath via
   `filename_or_fp` or `attachment_filename`.

.. versionchanged:: 0.12
   The `attachment_filename` is preferred over `filename` for MIME-type
   detection.

.. versionchanged:: 1.0
    UTF-8 filenames, as specified in `RFC 2231`_, are supported.

.. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4

.. versionchanged:: 1.0.3
    Filenames are encoded with ASCII instead of Latin-1 for broader
    compatibility with WSGI servers.

.. versionchanged:: 1.1
    Filename may be a :class:`~os.PathLike` object.

.. versionadded:: 1.1
    Partial content supports :class:`~io.BytesIO`.

:param filename_or_fp: the filename of the file to send.
                       This is relative to the :attr:`~Flask.root_path`
                       if a relative path is specified.
                       Alternatively a file object might be provided in
                       which case ``X-Sendfile`` might not work and fall
                       back to the traditional method.  Make sure that the
                       file pointer is positioned at the start of data to
                       send before calling :func:`send_file`.
:param mimetype: the mimetype of the file if provided. If a file path is
                 given, auto detection happens as fallback, otherwise an
                 error will be raised.
:param as_attachment: set to ``True`` if you want to send this file with
                      a ``Content-Disposition: attachment`` header.
:param attachment_filename: the filename for the attachment if it
                            differs from the file's filename.
:param add_etags: set to ``False`` to disable attaching of etags.
:param conditional: set to ``True`` to enable conditional responses.

:param cache_timeout: the timeout in seconds for the headers. When ``None``
                      (default), this value is set by
                      :meth:`~Flask.get_send_file_max_age` of
                      :data:`~flask.current_app`.
:param last_modified: set the ``Last-Modified`` header to this value,
    a :class:`~datetime.datetime` or timestamp.
    If a file was passed, this overrides its mtime.

◆ send_from_directory()

def flask.helpers.send_from_directory (   directory,
  filename,
**  options 
)
Send a file from a given directory with :func:`send_file`.  This
is a secure way to quickly expose static files from an upload folder
or something similar.

Example usage::

    @app.route('/uploads/<path:filename>')
    def download_file(filename):
        return send_from_directory(app.config['UPLOAD_FOLDER'],
                                   filename, as_attachment=True)

.. admonition:: Sending files and Performance

   It is strongly recommended to activate either ``X-Sendfile`` support in
   your webserver or (if no authentication happens) to tell the webserver
   to serve files for the given path on its own without calling into the
   web application for improved performance.

.. versionadded:: 0.5

:param directory: the directory where all the files are stored.
:param filename: the filename relative to that directory to
                 download.
:param options: optional keyword arguments that are directly
                forwarded to :func:`send_file`.

◆ stream_with_context()

def flask.helpers.stream_with_context (   generator_or_function)
Request contexts disappear when the response is started on the server.
This is done for efficiency reasons and to make it less likely to encounter
memory leaks with badly written WSGI middlewares.  The downside is that if
you are using streamed responses, the generator cannot access request bound
information any more.

This function however can help you keep the context around for longer::

    from flask import stream_with_context, request, Response

    @app.route('/stream')
    def streamed_response():
        @stream_with_context
        def generate():
            yield 'Hello '
            yield request.args['name']
            yield '!'
        return Response(generate())

Alternatively it can also be used around a specific generator::

    from flask import stream_with_context, request, Response

    @app.route('/stream')
    def streamed_response():
        def generate():
            yield 'Hello '
            yield request.args['name']
            yield '!'
        return Response(stream_with_context(generate()))

.. versionadded:: 0.9

◆ total_seconds()

def flask.helpers.total_seconds (   td)
Returns the total seconds from a timedelta object.

:param timedelta td: the timedelta to be converted in seconds

:returns: number of seconds
:rtype: int

◆ url_for()

def flask.helpers.url_for (   endpoint,
**  values 
)
Generates a URL to the given endpoint with the method provided.

Variable arguments that are unknown to the target endpoint are appended
to the generated URL as query arguments.  If the value of a query argument
is ``None``, the whole pair is skipped.  In case blueprints are active
you can shortcut references to the same blueprint by prefixing the
local endpoint with a dot (``.``).

This will reference the index function local to the current blueprint::

    url_for('.index')

For more information, head over to the :ref:`Quickstart <url-building>`.

Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when
generating URLs outside of a request context.

To integrate applications, :class:`Flask` has a hook to intercept URL build
errors through :attr:`Flask.url_build_error_handlers`.  The `url_for`
function results in a :exc:`~werkzeug.routing.BuildError` when the current
app does not have a URL for the given endpoint and values.  When it does, the
:data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
it is not ``None``, which can return a string to use as the result of
`url_for` (instead of `url_for`'s default to raise the
:exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
An example::

    def external_url_handler(error, endpoint, values):
        "Looks up an external URL when `url_for` cannot build a URL."
        # This is an example of hooking the build_error_handler.
        # Here, lookup_url is some utility function you've built
        # which looks up the endpoint in some external URL registry.
        url = lookup_url(endpoint, **values)
        if url is None:
            # External lookup did not have a URL.
            # Re-raise the BuildError, in context of original traceback.
            exc_type, exc_value, tb = sys.exc_info()
            if exc_value is error:
                raise exc_type, exc_value, tb
            else:
                raise error
        # url_for will use this result, instead of raising BuildError.
        return url

    app.url_build_error_handlers.append(external_url_handler)

Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
`endpoint` and `values` are the arguments passed into `url_for`.  Note
that this is for building URLs outside the current application, and not for
handling 404 NotFound errors.

.. versionadded:: 0.10
   The `_scheme` parameter was added.

.. versionadded:: 0.9
   The `_anchor` and `_method` parameters were added.

.. versionadded:: 0.9
   Calls :meth:`Flask.handle_build_error` on
   :exc:`~werkzeug.routing.BuildError`.

:param endpoint: the endpoint of the URL (name of the function)
:param values: the variable arguments of the URL rule
:param _external: if set to ``True``, an absolute URL is generated. Server
  address can be changed via ``SERVER_NAME`` configuration variable which
  falls back to the `Host` header, then to the IP and port of the request.
:param _scheme: a string specifying the desired URL scheme. The `_external`
  parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
  behavior uses the same scheme as the current request, or
  ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no
  request context is available. As of Werkzeug 0.10, this also can be set
  to an empty string to build protocol-relative URLs.
:param _anchor: if provided this is added as anchor to the URL.
:param _method: if provided this explicitly specifies an HTTP method.