module documentation

Undocumented

Class locked​_cached​_property A property that is only evaluated once. Like werkzeug.utils.cached_property except access uses a lock for thread safety.
Function ​_prepare​_send​_file​_kwargs Undocumented
Function ​_split​_blueprint​_path Undocumented
Function flash 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 get_flashed_messages.
Function get​_debug​_flag No summary
Function get​_env Get the environment the app is running in, indicated by the :envvar:`FLASK_ENV` environment variable. The default is 'production'.
Function get​_flashed​_messages No summary
Function get​_load​_dotenv Get whether the user has disabled loading dotenv files by setting :envvar:`FLASK_SKIP_DOTENV`. The default is True, load the files.
Function get​_root​_path Find the root path of a package, or the path that contains a module. If it cannot be found, returns the current working directory.
Function get​_template​_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:
Function is​_ip Determine if the given string is an IP address.
Function make​_response No summary
Function safe​_join Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory.
Function send​_file Send the contents of a file to the client.
Function send​_from​_directory Send a file from within a directory using send_file.
Function stream​_with​_context No summary
Function total​_seconds Returns the total seconds from a timedelta object.
Function url​_for Generates a URL to the given endpoint with the method provided.
def _prepare_send_file_kwargs(download_name=None, attachment_filename=None, etag=None, add_etags=None, max_age=None, cache_timeout=None, **kwargs):

Undocumented

Parameters
download​_name:t.Optional[str]Undocumented
attachment​_filename:t.Optional[str]Undocumented
etag:t.Optional[t.Union[bool, str]]Undocumented
add​_etags:t.Optional[t.Union[bool]]Undocumented
max​_age:t.Optional[t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]]Undocumented
cache​_timeout:t.Optional[int]Undocumented
**kwargs:t.AnyUndocumented
Returns
t.Dict[str, t.Any]Undocumented
@lru_cache(maxsize=None)
def _split_blueprint_path(name):

Undocumented

Parameters
name:strUndocumented
Returns
t.List[str]Undocumented
def 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 get_flashed_messages.

Changed in version 0.3: category parameter added.
Parameters
message:strthe message to be flashed.
category:strthe 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.
def 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 .get_env returns 'development', or False otherwise.
Returns
boolUndocumented
def get_env():
Get the environment the app is running in, indicated by the :envvar:`FLASK_ENV` environment variable. The default is 'production'.
Returns
strUndocumented
def 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 :doc:`/patterns/flashing` for examples.

Changed in version 0.3: with_categories parameter added.
Changed in version 0.9: category_filter parameter added.
Parameters
with​_categories:boolset to True to also receive categories.
category​_filter:t.Iterable[str]filter of categories to limit return values. Only categories in the list will be returned.
Returns
t.Union[t.List[str], t.List[t.Tuple[str, str]]]Undocumented
def 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.
Parameters
default:boolWhat to return if the env var isn't set.
Returns
boolUndocumented
def get_root_path(import_name):

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 find_package.

Parameters
import​_name:strUndocumented
Returns
strUndocumented
Unknown Field: meta
private
def 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:

{% 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')
New in version 0.2.
Parameters
template​_name:strthe name of the template
attribute:strthe name of the variable of macro to access
Returns
t.AnyUndocumented
def is_ip(value):
Determine if the given string is an IP address.
Parameters
value:strvalue to check
Returns
boolTrue if string is an IP address
def 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, flask.Flask.make_response is invoked with it.
  • if more than one argument is passed, the arguments are passed to the flask.Flask.make_response function as tuple.
New in version 0.6.
Parameters
*args:t.AnyUndocumented
Returns
ResponseUndocumented
def safe_join(directory, *pathnames):
Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory.
Parameters
directory:strThe trusted base directory.
*pathnames:strThe untrusted path components relative to the base directory.
Returns
strA safe path, otherwise None.
def send_file(path_or_file, mimetype=None, as_attachment=False, download_name=None, attachment_filename=None, conditional=True, etag=True, add_etags=None, last_modified=None, max_age=None, cache_timeout=None):

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 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 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.

Changed in version 2.0: download_name replaces the attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead.
Changed in version 2.0: max_age replaces the cache_timeout parameter. conditional is enabled and max_age is not set by default.
Changed in version 2.0: etag replaces the add_etags parameter. It can be a string to use instead of generating one.
Changed in version 2.0: Passing a file-like object that inherits from ~io.TextIOBase will raise a ValueError rather than sending an empty file.
New in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.
Changed in version 1.1: filename may be a ~os.PathLike object.
Changed in version 1.1: Passing a ~io.BytesIO object supports range requests.
Changed in version 1.0.3: Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers.
Changed in version 1.0: UTF-8 filenames as specified in RFC 2231 are supported.
Changed in version 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.
Changed in version 0.12: attachment_filename is preferred over filename for MIME detection.
Changed in version 0.9: cache_timeout defaults to Flask.get_send_file_max_age.
Changed in version 0.7: MIME guessing and etag support for file-like objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself.
Changed in version 0.5: The add_etags, cache_timeout and conditional parameters were added. The default behavior is to add etags.
New in version 0.2.
Parameters
path​_or​_file:t.Union[os.PathLike, str, t.BinaryIO]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.
mimetype:t.Optional[str]The MIME type to send for the file. If not provided, it will try to detect it from the file name.
as​_attachment:boolIndicate to a browser that it should offer to save the file instead of displaying it.
download​_name:t.Optional[str]The default name browsers will use when saving the file. Defaults to the passed file name.
attachment​_filename:t.Optional[str]Undocumented
conditional:boolEnable conditional and range responses based on request headers. Requires passing a file path and environ.
etag:t.Union[bool, str]Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead.
add​_etags:t.Optional[bool]Undocumented
last​_modified:t.Optional[t.Union[datetime, int, float]]The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path.
max​_age:t.Optional[t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]]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.
cache​_timeout:t.Optional[int]Undocumented
def send_from_directory(directory, path, filename=None, **kwargs):

Send a file from within a directory using send_file.

@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 ~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 ~werkzeug.exceptions.NotFound error.

Changed in version 2.0: path replaces the filename parameter.
New in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.
New in version 0.5.
Parameters
directory:t.Union[os.PathLike, str]The directory that path must be located under.
path:t.Union[os.PathLike, str]The path to the file to send, relative to directory.
filename:t.Optional[str]Undocumented
**kwargs:t.AnyArguments to pass to send_file.
Returns
ResponseUndocumented
def 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()))
New in version 0.9.
Parameters
generator​_or​_function:t.Union[t.Iterator[t.AnyStr], t.Callable[..., t.Iterator[t.AnyStr]]]Undocumented
Returns
t.Iterator[t.AnyStr]Undocumented
def total_seconds(td):

Returns the total seconds from a timedelta object.

Deprecated since version 2.0: Will be removed in Flask 2.1. Use timedelta.total_seconds instead.
Parameters
td:timedeltaUndocumented
timedelta tdthe timedelta to be converted in seconds
Returns
intnumber of seconds
def 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')

See :ref:`url-building`.

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

To integrate applications, Flask has a hook to intercept URL build errors through Flask.url_build_error_handlers. The url_for function results in a ~werkzeug.routing.BuildError when the current app does not have a URL for the given endpoint and values. When it does, the ~flask.current_app calls its ~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 ~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).with_traceback(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 ~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.

New in version 0.10: The _scheme parameter was added.
New in version 0.9: The _anchor and _method parameters were added.
New in version 0.9: Calls Flask.handle_build_error on ~werkzeug.routing.BuildError.
Parameters
endpoint:strthe endpoint of the URL (name of the function)
**values:t.Anythe variable arguments of the URL rule
​_externalif 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.
​_schemea string specifying the desired URL scheme. The _external parameter must be set to True or a ValueError is raised. The default behavior uses the same scheme as the current request, or PREFERRED_URL_SCHEME if no request context is available. This also can be set to an empty string to build protocol-relative URLs.
​_anchorif provided this is added as anchor to the URL.
​_methodif provided this explicitly specifies an HTTP method.
Returns
strUndocumented