flask.Flask

class flask.Flask(import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None)[source]

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 __init__.py file inside) or a standard module (just a .py file).

For more information about resource loading, see open_resource().

Usually you create a Flask instance in your main module or in the __init__.py file of your package like this:

from flask import Flask
app = Flask(__name__)

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

New in version 0.7: The static_url_path, static_folder, and template_folder parameters were added.

New in version 0.8: The instance_path and instance_relative_config parameters were added.

New in version 0.11: The root_path parameter was added.

Parameters:
  • import_name – the name of the application package
  • 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.
  • static_folder – the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.
  • 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.
  • 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.
  • 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.
  • root_path – Flask by default will automatically calculate the path to the root of the application. In certain situations this cannot be achieved (for instance if the package is a Python 3 namespace package) and needs to be manually defined.

Methods

__init__(import_name[, static_path, ...])
add_template_filter(*args, **kwargs) Register a custom template filter.
add_template_global(*args, **kwargs) Register a custom template global function.
add_template_test(*args, **kwargs) Register a custom template test.
add_url_rule(*args, **kwargs) Connects a URL rule.
after_request(*args, **kwargs) Register a function to be run after each request.
app_context() Binds the application only.
auto_find_instance_path() Tries to locate the instance path if it was not provided to the constructor of the application class.
before_first_request(*args, **kwargs) Registers a function to be run before the first request to this instance of the application.
before_request(*args, **kwargs) Registers a function to run before each request.
context_processor(*args, **kwargs) Registers a template context processor function.
create_global_jinja_loader() Creates the loader for the Jinja2 environment.
create_jinja_environment() Creates the Jinja2 environment based on jinja_options and select_jinja_autoescape().
create_url_adapter(request) Creates a URL adapter for the given request.
dispatch_request() Does the request dispatching.
do_teardown_appcontext([exc]) Called when an application context is popped.
do_teardown_request([exc]) Called after the actual request dispatching and will call every as teardown_request() decorated function.
endpoint(*args, **kwargs) A decorator to register a function as an endpoint.
errorhandler(*args, **kwargs) A decorator that is used to register a function give a given error code.
full_dispatch_request() Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
get_send_file_max_age(filename) Provides default cache_timeout for the send_file() functions.
handle_exception(e) Default exception handling that kicks in when an exception occurs that is not caught.
handle_http_exception(e) Handles an HTTP exception.
handle_url_build_error(error, endpoint, values) Handle BuildError on url_for().
handle_user_exception(e) This method is called whenever an exception occurs that should be handled.
init_jinja_globals() Deprecated.
inject_url_defaults(endpoint, values) Injects the URL defaults for the given endpoint directly into the values dictionary passed.
iter_blueprints() Iterates over all blueprints by the order they were registered.
log_exception(exc_info) Logs an exception.
make_config([instance_relative]) Used to create the config attribute by the Flask constructor.
make_default_options_response() This method is called to create the default OPTIONS response.
make_null_session() Creates a new instance of a missing session.
make_response(rv) Converts the return value from a view function to a real response object that is an instance of response_class.
make_shell_context() Returns the shell context for an interactive shell for this application.
open_instance_resource(resource[, mode]) Opens a resource from the application’s instance folder (instance_path).
open_resource(resource[, mode]) Opens a resource from the application’s resource folder.
open_session(request) Creates or opens a new session.
preprocess_request() Called before the actual request dispatching and will call each before_request() decorated function, passing no arguments.
process_response(response) Can be overridden in order to modify the response object before it’s sent to the WSGI server.
raise_routing_exception(request) Exceptions that are recording during routing are reraised with this method.
register_blueprint(*args, **kwargs) Register a blueprint on the application.
register_error_handler(code_or_exception, f) Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage.
request_context(environ) Creates a RequestContext from the given environment and binds it to the current context.
route(rule, **options) A decorator that is used to register a view function for a given URL rule.
run([host, port, debug]) Runs the application on a local development server.
save_session(session, response) Saves the session if it needs updates.
select_jinja_autoescape(filename) Returns True if autoescaping should be active for the given template name.
send_static_file(filename) Function used internally to send static files from the static folder to the browser.
shell_context_processor(*args, **kwargs) Registers a shell context processor function.
should_ignore_error(error) This is called to figure out if an error should be ignored or not as far as the teardown system is concerned.
teardown_appcontext(*args, **kwargs) Registers a function to be called when the application context ends.
teardown_request(*args, **kwargs) Register a function to be run at the end of each request, regardless of whether there was an exception or not.
template_filter(*args, **kwargs) A decorator that is used to register custom template filter.
template_global(*args, **kwargs) A decorator that is used to register a custom template global function.
template_test(*args, **kwargs) A decorator that is used to register custom template test.
test_client([use_cookies]) Creates a test client for this application.
test_request_context(*args, **kwargs) Creates a WSGI environment from the given values (see werkzeug.test.EnvironBuilder for more information, this function accepts the same arguments).
trap_http_exception(e) Checks if an HTTP exception should be trapped or not.
try_trigger_before_first_request_functions() Called before each request and will ensure that it triggers the before_first_request_funcs and only exactly once per application instance (which means process usually).
update_template_context(context) Update the template context with some commonly used variables.
url_defaults(*args, **kwargs) Callback function for URL defaults for all view functions of the application.
url_value_preprocessor(*args, **kwargs) Registers a function as URL value preprocessor for all view functions of the application.
wsgi_app(environ, start_response) The actual WSGI application.

Attributes

debug The debug flag.
default_config Default configuration parameters.
error_handlers
got_first_request This attribute is set to True if the application started handling the first request.
has_static_folder This is True if the package bound object’s container has a folder for static files.
jinja_env The Jinja2 environment used to load templates.
jinja_loader The Jinja loader for this package bound object.
jinja_options Options that are passed directly to the Jinja2 environment.
logger A logging.Logger object for this application.
logger_name The name of the logger to use.
name The name of the application.
permanent_session_lifetime A timedelta which is used to set the expiration date of a permanent session.
preserve_context_on_exception Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it’s set, otherwise a sensible default is returned.
propagate_exceptions Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it’s set, otherwise a sensible default is returned.
request_globals_class
secret_key If a secret key is set, cryptographic components can use this to sign cookies and other things.
send_file_max_age_default A timedelta which is used as default cache_timeout for the send_file() functions.
session_cookie_name The secure cookie uses this for the name of the session cookie.
session_interface the session interface to use. By default an instance of
static_folder The absolute path to the configured static folder.
static_url_path
test_client_class the test client that is used with when test_client is used.
testing The testing flag.
use_x_sendfile Enable this if you want to use the X-Sendfile feature.