API

This part of the documentation covers all the interfaces of Flask. Forparts where Flask depends on external libraries, we document the mostimportant right here and provide links to the canonical documentation.

Application Object

  • class flask.``Flask(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None)
  • The flask object implements a WSGI application and acts as the centralobject. It is passed the name of the module or package of theapplication. Once it is created it will act as a central registry forthe view functions, the URL rules, template configuration and much more.

The name of the package is used to resolve resources from inside thepackage or the folder the module is contained in depending on if thepackage parameter resolves to an actual python package (a folder withan 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 orin the init.py file of your package like this:

1. from flask import Flask
2. app = Flask(__name__)

About the First Parameter

The idea of the first parameter is to give Flask an idea of whatbelongs to your application. This name is used to find resourceson the filesystem, can be used by extensions to improve debugginginformation and a lot more.

So it’s important what you provide there. If you are using a singlemodule, name is always the correct value. If you however areusing a package, it’s usually recommended to hardcode the name ofyour package there.

For example if your application is defined in yourapplication/app.pyyou should create it with one of the two versions below:

1. app = Flask('yourapplication')
2. app = Flask(__name__.split('.')[0])

Why is that? The application will work even with name, thanksto how resources are looked up. However it will make debugging morepainful. Certain extensions can make assumptions based on theimport name of your application. For example the Flask-SQLAlchemyextension will look for the code in your application that triggeredan SQL query in debug mode. If the import name is not properly setup, that debugging information is lost. (For example it would onlypick up SQL queries in yourapplication.app and notyourapplication.views.frontend)

Changelog

New in version 1.0: The host_matching and static_host parameters were added.

New in version 1.0: The subdomain_matching parameter was added. Subdomainmatching needs to be enabled manually now. SettingSERVER_NAME does not implicitly enable it.

New in version 0.11: The root_path parameter was added.

New in version 0.8: The instance_path and instance_relative_config parameters wereadded.

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

  • Parameters
    • import_name – the name of the application package
  • static_url_path – can be used to specify a different path for thestatic files on the web. Defaults to the nameof the static_folder folder.
  • static_folder – the folder with static files that should be servedat static_url_path. Defaults to the 'static'folder in the root path of the application.
  • static_host – the host to use when adding the static route.Defaults to None. Required when using host_matching=Truewith a static_folder configured.
  • host_matching – set url_map.host_matching attribute.Defaults to False.
  • subdomain_matching – consider the subdomain relative toSERVER_NAME when matching routes. Defaults to False.
  • template_folder – the folder that contains the templates that shouldbe used by the application. Defaults to'templates' folder in the root path of theapplication.
  • instance_path – An alternative instance path for the application.By default the folder 'instance' next to thepackage or module is assumed to be the instancepath.
  • instance_relative_config – if set to True relative filenamesfor loading the config are assumed tobe relative to the instance path insteadof the application root.
  • root_path – Flask by default will automatically calculate the pathto the root of the application. In certain situationsthis cannot be achieved (for instance if the packageis a Python 3 namespace package) and needs to bemanually defined.
  • addtemplate_filter(_f, name=None)
  • Register a custom template filter. Works exactly like thetemplate_filter() decorator.

  • Parameters

  • name – the optional name of the filter, otherwise thefunction name will be used.
  • addtemplate_global(_f, name=None)
  • Register a custom template global function. Works exactly like thetemplate_global() decorator.Changelog

New in version 0.10.

1. - Parameters
2. -

name – the optional name of the global function, otherwise thefunction name will be used.

  • addtemplate_test(_f, name=None)
  • Register a custom template test. Works exactly like thetemplate_test() decorator.Changelog

New in version 0.10.

1. - Parameters
2. -

name – the optional name of the test, otherwise thefunction name will be used.

  • addurl_rule(_rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)
  • Connects a URL rule. Works exactly like the route()decorator. If a view_func is provided it will be registered with theendpoint.

Basically this example:

1. @app.route('/')def index():    pass

Is equivalent to the following:

1. def index():
2. pass
3. app.add_url_rule('/', 'index', index)

If the view_func is not provided you will need to connect the endpointto a view function like so:

1. app.view_functions['index'] = index

Internally route() invokes add_url_rule() so if you wantto customize the behavior via subclassing you only need to changethis method.

For more information refer to URL Route Registrations.Changelog

Changed in version 0.6: OPTIONS is added automatically as method.

Changed in version 0.2: view_func parameter added.

1. - Parameters
2. -
3. -

rule – the URL rule as string

1. -

endpoint – the endpoint for the registered URL rule. Flaskitself assumes the name of the view function asendpoint

1. -

view_func – the function to call when serving a request to theprovided endpoint

1. -

provide_automatic_options – controls whether the OPTIONSmethod should be added automatically. This can also be controlledby setting the view_func.provide_automatic_options = Falsebefore adding the rule.

1. -

options – the options to be forwarded to the underlyingRule object. A changeto Werkzeug is handling of method options. methodsis a list of methods this rule should be limitedto (GET, POST etc.). By default a rulejust listens for GET (and implicitly HEAD).Starting with Flask 0.6, OPTIONS is implicitlyadded and handled by the standard request handling.

  • afterrequest(_f)
  • Register a function to be run after each request.

Your function must take one parameter, an instance ofresponse_class and return a new response object or thesame (see process_response()).

As of Flask 0.7 this function might not be executed at the end of therequest in case an unhandled exception occurred.

  • afterrequest_funcs = None_
  • A dictionary with lists of functions that should be called aftereach request. The key of the dictionary is the name of the blueprintthis function is active for, None for all requests. This can forexample be used to close database connections. To register a functionhere, use the after_request() decorator.
  • app_context()
  • Create an AppContext. Use as a withblock to push the context, which will make current_apppoint at this application.

An application context is automatically pushed byRequestContext.push()when handling a request, and when running a CLI command. Usethis to manually create a context outside of these situations.

1. with app.app_context():
2. init_db()

See The Application Context.Changelog

New in version 0.9.

  • app_ctx_globals_class
  • alias of flask.ctx._AppCtxGlobals
  • auto_find_instance_path()
  • Tries to locate the instance path if it was not provided to theconstructor of the application class. It will basically calculatethe path to a folder named instance next to your main file orthe package.Changelog

New in version 0.8.

  • beforefirst_request(_f)
  • Registers a function to be run before the first request to thisinstance of the application.

The function will be called without any arguments and its returnvalue is ignored.Changelog

New in version 0.8.

  • beforefirst_request_funcs = None_
  • A list of functions that will be called at the beginning of thefirst request to this instance. To register a function, use thebefore_first_request() decorator.Changelog

New in version 0.8.

  • beforerequest(_f)
  • Registers a function to run before each request.

For example, this can be used to open a database connection, or to loadthe logged in user from the session.

The function will be called without any arguments. If it returns anon-None value, the value is handled as if it was the return value fromthe view, and further request handling is stopped.

  • beforerequest_funcs = None_
  • A dictionary with lists of functions that will be called at thebeginning of each request. The key of the dictionary is the name ofthe blueprint this function is active for, or None for allrequests. To register a function, use the before_request()decorator.
  • blueprints = None
  • all the attached blueprints in a dictionary by name. Blueprintscan be attached multiple times so this dictionary does not tellyou how often they got attached.Changelog

New in version 0.7.

  • config = None
  • The configuration dictionary as Config. This behavesexactly like a regular dictionary but supports additional methodsto load a config from files.
  • config_class
  • alias of flask.config.Config
  • contextprocessor(_f)
  • Registers a template context processor function.
  • create_global_jinja_loader()
  • Creates the loader for the Jinja2 environment. Can be used tooverride just the loader and keeping the rest unchanged. It’sdiscouraged to override this function. Instead one should overridethe jinja_loader() function instead.

The global loader dispatches between the loaders of the applicationand the individual blueprints.Changelog

New in version 0.7.

  • create_jinja_environment()
  • Create the Jinja environment based on jinja_optionsand the various Jinja-related methods of the app. Changingjinja_options after this will have no effect. Also addsFlask-related globals and filters to the environment.Changelog

Changed in version 0.11: Environment.auto_reload set in accordance withTEMPLATES_AUTO_RELOAD configuration option.

New in version 0.5.

  • createurl_adapter(_request)
  • Creates a URL adapter for the given request. The URL adapteris created at a point where the request context is not yet setup so the request is passed explicitly.Changelog

Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomainmatching. Use subdomain_matching instead.

Changed in version 0.9: This can now also be called without a request object when theURL adapter is created for the application context.

New in version 0.6.

  • property debug
  • Whether debug mode is enabled. When using flask run to startthe development server, an interactive debugger will be shown forunhandled exceptions, and the server will be reloaded when codechanges. This maps to the DEBUG config key. This isenabled when env is 'development' and is overriddenby the FLASK_DEBUG environment variable. It may not behave asexpected if set in code.

Do not enable debug mode when deploying in production.

Default: True if env is 'development', orFalse otherwise.

  • defaultconfig = {'APPLICATIONROOT': '/', 'DEBUG': None, 'ENV': None, 'EXPLAIN_TEMPLATE_LOADING': False, 'JSONIFY_MIMETYPE': 'application/json', 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'MAX_CONTENT_LENGTH': None, 'MAX_COOKIE_SIZE': 4093, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'PREFERRED_URL_SCHEME': 'http', 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'SERVER_NAME': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'TEMPLATES_AUTO_RELOAD': None, 'TESTING': False, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'USE_X_SENDFILE': False}
  • Default configuration parameters.
  • dispatch_request()
  • Does the request dispatching. Matches the URL and returns thereturn value of the view or error handler. This does not have tobe a response object. In order to convert the return value to aproper response object, call make_response().Changelog

Changed in version 0.7: This no longer does the exception handling, this code wasmoved to the new full_dispatch_request().

  • doteardown_appcontext*(_exc=)- Called right before the application context is popped.

When handling a request, the application context is poppedafter the request context. See do_teardown_request().

This calls all functions decorated withteardown_appcontext(). Then theappcontext_tearing_down signal is sent.

This is called byAppContext.pop().Changelog

New in version 0.9.

  • doteardown_request*(_exc=)- Called after the request is dispatched and the response isreturned, right before the request context is popped.

    This calls all functions decorated withteardown_request(), and Blueprint.teardown_request()if a blueprint handled the request. Finally, therequest_tearing_down signal is sent.

    This is called byRequestContext.pop(),which may be delayed during testing to maintain access toresources.

    1. - Parameters 2. -

    exc – An unhandled exception raised while dispatching therequest. Detected from the current exception information ifnot passed. Passed to each teardown function.Changelog

    Changed in version 0.9: Added the exc argument.

    • endpoint(endpoint)
    • A decorator to register a function as an endpoint.Example:

    @app.endpoint('example.endpoint')def example(): return "example"

    - Parameters -

    endpoint – the name of the endpoint

    • env
    • What environment the app is running in. Flask and extensions mayenable behaviors based on the environment, such as enabling debugmode. This maps to the ENV config key. This is set by theFLASK_ENV environment variable and may not behave asexpected if set in code.

    Do not enable development when deploying in production.

    Default: 'production'

    • errorhandler_spec = None_
    • A dictionary of all registered error handlers. The key is Nonefor error handlers active on the application, otherwise the key isthe name of the blueprint. Each key points to another dictionarywhere the key is the status code of the http exception. Thespecial key None points to a list of tuples where the first itemis the class for the instance check and the second the error handlerfunction.

    To register an error handler, use the errorhandler()decorator.

    • errorhandler(code_or_exception)
    • Register a function to handle errors by code or exception class.

    A decorator that is used to register a function given anerror code. Example:

    @app.errorhandler(404)def page_not_found(error): return 'This page does not exist', 404

    You can also register handlers for arbitrary exceptions:

    @app.errorhandler(DatabaseError)def special_exception_handler(error): return 'Database connection failed', 500

    Changelog

    New in version 0.7: Use register_error_handler() instead of modifyingerror_handler_spec directly, for application wide errorhandlers.

    New in version 0.7: One can now additionally also register custom exception typesthat do not necessarily have to be a subclass of theHTTPException class.

    - Parameters -

    code_or_exception – the code as integer for the handler, oran arbitrary exception

    • extensions = None
    • a place where extensions can store application specific state. Forexample this is where an extension could store database engines andsimilar things. For backwards compatibility extensions should registerthemselves like this:

    if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['extensionname'] = SomeObject()

    The key must match the name of the extension module. For example incase of a “Flask-Foo” extension in flask_foo, the key would be'foo'.Changelog

    New in version 0.7.

    • full_dispatch_request()
    • Dispatches the request and on top of that performs requestpre and postprocessing as well as HTTP exception catching anderror handling.Changelog

    New in version 0.7.

    • getsend_file_max_age(_filename)
    • Provides default cache_timeout for the send_file() functions.

    By default, this function returns SEND_FILE_MAX_AGE_DEFAULT fromthe configuration of current_app.

    Static file functions such as send_from_directory() use thisfunction, and send_file() calls this function oncurrent_app when the given cache_timeout is None. If acache_timeout is given in send_file(), that timeout is used;otherwise, this method is called.

    This allows subclasses to change the behavior when sending files basedon the filename. For example, to set the cache timeout for .js filesto 60 seconds:

    class MyFlask(flask.Flask): def get_send_file_max_age(self, name): if name.lower().endswith('.js'): return 60 return flask.Flask.get_send_file_max_age(self, name)

    Changelog

    New in version 0.9.

    • property got_first_request
    • This attribute is set to True if the application startedhandling the first request.Changelog

    New in version 0.8.

    • handleexception(_e)
    • Handle an exception that did not have an error handlerassociated with it, or that was raised from an error handler.This always causes a 500 InternalServerError.

    Always sends the got_request_exception signal.

    If propagate_exceptions is True, such as in debugmode, the error will be re-raised so that the debugger candisplay it. Otherwise, the original exception is logged, andan InternalServerError is returned.

    If an error handler is registered for InternalServerError or500, it will be used. For consistency, the handler willalways receive the InternalServerError. The originalunhandled exception is available as e.original_exception.

    Note

    Prior to Werkzeug 1.0.0, InternalServerError will notalways have an original_exception attribute. Usegetattr(e, "original_exception", None) to simulate thebehavior for compatibility.

    Changed in version 1.1.0: Always passes the InternalServerError instance to thehandler, setting original_exception to the unhandlederror.

    Changed in version 1.1.0: after_request functions and other finalization is doneeven for the default 500 response when there is no handler.

    Changelog

    New in version 0.3.

    • handlehttp_exception(_e)
    • Handles an HTTP exception. By default this will invoke theregistered error handlers and fall back to returning theexception as response.Changelog

    Changed in version 1.0.3: RoutingException, used internally for actions such as slash redirects during routing, is not passed to error handlers.

    Changed in version 1.0: Exceptions are looked up by code and by MRO, soHTTPExcpetion subclasses can be handled with a catch-allhandler for the base HTTPException.

    New in version 0.3.

    • handleurl_build_error(_error, endpoint, values)
    • Handle BuildError on url_for().
    • handleuser_exception(_e)
    • This method is called whenever an exception occurs thatshould be handled. A special case is HTTPException which is forwarded to thehandle_http_exception() method. This function will eitherreturn a response value or reraise the exception with the sametraceback.Changelog

    Changed in version 1.0: Key errors raised from request data like form show thebad key in debug mode rather than a generic bad requestmessage.

    New in version 0.7.

    • property has_static_folder
    • This is True if the package bound object’s container has afolder for static files.Changelog

    New in version 0.5.

    • importname = None_
    • The name of the package or module that this app belongs to. Do notchange this once it is set by the constructor.
    • injecturl_defaults(_endpoint, values)
    • Injects the URL defaults for the given endpoint directly intothe values dictionary passed. This is used internally andautomatically called on URL building.Changelog

    New in version 0.7.

    • instancepath = None_
    • Holds the path to the instance folder.Changelog

    New in version 0.8.

    • iter_blueprints()
    • Iterates over all blueprints by the order they were registered.Changelog

    New in version 0.11.

    • jinja_env
    • The Jinja environment used to load templates.

    The environment is created the first time this property isaccessed. Changing jinja_options after that will have noeffect.

    • jinja_environment
    • alias of flask.templating.Environment
    • jinja_loader
    • The Jinja loader for this package bound object.Changelog

    New in version 0.5.

    • jinjaoptions = {'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with']}
    • Options that are passed to the Jinja environment increate_jinja_environment(). Changing these options afterthe environment is created (accessing jinja_env) willhave no effect.

    Changed in version 1.1.0: This is a dict instead of an ImmutableDict to alloweasier configuration.

    New in version 0.8.

    • logger
    • A standard Python Logger for the app, withthe same name as name.

    In debug mode, the logger’s level willbe set to DEBUG.

    If there are no handlers configured, a default handler will beadded. See Logging for more information.

    Changed in version 1.1.0: The logger takes the same name as name rather thanhard-coding "flask.app".

    Changelog

    Changed in version 1.0.0: Behavior was simplified. The logger is always named"flask.app". The level is only set during configuration,it doesn’t check app.debug each time. Only one format isused, not different ones depending on app.debug. Nohandlers are removed, and a handler is only added if nohandlers are already configured.

    New in version 0.3.

    • makeconfig(_instance_relative=False)
    • Used to create the config attribute by the Flask constructor.The instance_relative parameter is passed in from the constructorof Flask (there named instance_relative_config) and indicates ifthe config should be relative to the instance path or the root pathof the application.Changelog

    New in version 0.8.

    • make_default_options_response()
    • This method is called to create the default OPTIONS response.This can be changed through subclassing to change the defaultbehavior of OPTIONS responses.Changelog

    New in version 0.7.

    • make_null_session()
    • Creates a new instance of a missing session. Instead of overridingthis method we recommend replacing the session_interface.Changelog

    New in version 0.7.

    • makeresponse(_rv)
    • Convert the return value from a view function to an instance ofresponse_class.

    • Parameters

    • rv –

    the return value from the view function. The view functionmust return a response. Returning None, or the view endingwithout returning, is not allowed. The following types are allowedfor view_rv:

    - <code>str</code> (<code>unicode</code> in Python 2) -

    A response object is created with the string encoded to UTF-8as the body.

    - <code>bytes</code> (<code>str</code> in Python 2) -

    A response object is created with the bytes as the body.

    - <code>dict</code> -

    A dictionary that will be jsonify’d before being returned.

    - <code>tuple</code> -

    Either (body, status, headers), (body, status), or(body, headers), where body is any of the other typesallowed here, status is a string or an integer, andheaders is a dictionary or a list of (key, value)tuples. If body is a response_class instance,status overwrites the exiting value and headers areextended.

    - [<code>response_class</code>]($e39a0602f3bae24b.md#flask.Flask.response_class) -

    The object is returned unchanged.

    - other [<code>Response</code>](https://werkzeug.palletsprojects.com/en/0.15.x/wrappers/#werkzeug.wrappers.Response) class -

    The object is coerced to response_class.

    - [<code>callable()</code>](https://docs.python.org/3/library/functions.html#callable) -

    The function is called as a WSGI application. The result isused to create a response object.

    Changelog

    Changed in version 0.9: Previously a tuple was interpreted as the arguments for theresponse object.

    • make_shell_context()
    • Returns the shell context for an interactive shell for thisapplication. This runs all the registered shell contextprocessors.Changelog

    New in version 0.11.

    • name
    • The name of the application. This is usually the import namewith the difference that it’s guessed from the run file if theimport name is main. This name is used as a display name whenFlask needs the name of the application. It can be set and overriddento change the value.Changelog

    New in version 0.8.

    • openinstance_resource(_resource, mode='rb')
    • Opens a resource from the application’s instance folder(instance_path). Otherwise works likeopen_resource(). Instance resources can also be opened forwriting.

    • Parameters

      • resource – the name of the resource. To access resources withinsubfolders use forward slashes as separator.
      • mode – resource file opening mode, default is ‘rb’.
    • openresource(_resource, mode='rb')
    • Opens a resource from the application’s resource folder. To seehow this works, consider the following folder structure:

    /myapplication.py /schema.sql /static /style.css /templates /layout.html /index.html

    If you want to open the schema.sql file you would do thefollowing:

    with app.open_resource('schema.sql') as f: contents = f.read() do_something_with(contents)

    - Parameters - -

    resource – the name of the resource. To access resources withinsubfolders use forward slashes as separator.

    -

    mode – Open file in this mode. Only reading is supported,valid values are “r” (or “rt”) and “rb”.

    • opensession(_request)
    • Creates or opens a new session. Default implementation stores allsession data in a signed cookie. This requires that thesecret_key is set. Instead of overriding this methodwe recommend replacing the session_interface.

    • Parameters

    • request – an instance of request_class.
    • permanent_session_lifetime
    • A timedelta which is used to set the expirationdate of a permanent session. The default is 31 days which makes apermanent session survive for roughly one month.

    This attribute can also be configured from the config with thePERMANENT_SESSION_LIFETIME configuration key. Defaults totimedelta(days=31)

    • preprocess_request()
    • Called before the request is dispatched. Callsurl_value_preprocessors registered with the app and thecurrent blueprint (if any). Then calls before_request_funcsregistered with the app and the blueprint.

    If any before_request() handler returns a non-None value, thevalue is handled as if it was the return value from the view, andfurther request handling is stopped.

    • property preserve_context_on_exception
    • Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTIONconfiguration value in case it’s set, otherwise a sensible defaultis returned.Changelog

    New in version 0.7.

    • processresponse(_response)
    • Can be overridden in order to modify the response objectbefore it’s sent to the WSGI server. By default this willcall all the after_request() decorated functions.Changelog

    Changed in version 0.5: As of Flask 0.5 the functions registered for after requestexecution are called in reverse order of registration.

    - Parameters -

    response – a response_class object.

    - Returns -

    a new response object or the same, has to be aninstance of response_class.

    • property propagate_exceptions
    • Returns the value of the PROPAGATE_EXCEPTIONS configurationvalue in case it’s set, otherwise a sensible default is returned.Changelog

    New in version 0.7.

    • registerblueprint(_blueprint, **options)
    • Register a Blueprint on the application. Keywordarguments passed to this method will override the defaults set on theblueprint.

    Calls the blueprint’s register() method afterrecording the blueprint in the application’s blueprints.

    - Parameters - -

    blueprint – The blueprint to register.

    -

    url_prefix – Blueprint routes will be prefixed with this.

    -

    subdomain – Blueprint routes will match on this subdomain.

    -

    url_defaults – Blueprint routes will use these default values forview arguments.

    -

    options – Additional keyword arguments are passed toBlueprintSetupState. They can beaccessed in record() callbacks.Changelog

    New in version 0.7.

    • registererror_handler(_code_or_exception, f)
    • Alternative error attach function to the errorhandler()decorator that is more straightforward to use for non decoratorusage.Changelog

    New in version 0.7.

    • request_class
    • alias of flask.wrappers.Request
    • requestcontext(_environ)
    • Create a RequestContext representing aWSGI environment. Use a with block to push the context,which will make request point at this request.

    See The Request Context.

    Typically you should not call this from your own code. A requestcontext is automatically pushed by the wsgi_app() whenhandling a request. Use test_request_context() to createan environment and context instead of this method.

    - Parameters -

    environ – a WSGI environment

    • response_class
    • alias of flask.wrappers.Response
    • rootpath = None_
    • Absolute path to the package on the filesystem. Used to look upresources contained in the package.
    • route(rule, **options)
    • A decorator that is used to register a view function for agiven URL rule. This does the same thing as add_url_rule()but is intended for decorator usage:

    @app.route('/')def index(): return 'Hello World'

    For more information refer to URL Route Registrations.

    - Parameters - -

    rule – the URL rule as string

    -

    endpoint – the endpoint for the registered URL rule. Flaskitself assumes the name of the view function asendpoint

    -

    options – the options to be forwarded to the underlyingRule object. A changeto Werkzeug is handling of method options. methodsis a list of methods this rule should be limitedto (GET, POST etc.). By default a rulejust listens for GET (and implicitly HEAD).Starting with Flask 0.6, OPTIONS is implicitlyadded and handled by the standard request handling.

    • run(host=None, port=None, debug=None, load_dotenv=True, **options)
    • Runs the application on a local development server.

    Do not use run() in a production setting. It is not intended tomeet security and performance requirements for a production server.Instead, see Deployment Options for WSGI server recommendations.

    If the debug flag is set the server will automatically reloadfor code changes and show a debugger in case an exception happened.

    If you want to run the application in debug mode, but disable thecode execution on the interactive debugger, you can passuse_evalex=False as parameter. This will keep the debugger’straceback screen active, but disable code execution.

    It is not recommended to use this function for development withautomatic reloading as this is badly supported. Instead you shouldbe using the flask command line script’s run support.

    Keep in Mind

    Flask will suppress any server error with a generic error pageunless it is in debug mode. As such to enable just theinteractive debugger without the code reloading, you have toinvoke run() with debug=True and use_reloader=False.Setting use_debugger to True without being in debug modewon’t catch any exceptions because there won’t be any tocatch.

    - Parameters - -

    host – the hostname to listen on. Set this to '0.0.0.0' tohave the server available externally as well. Defaults to'127.0.0.1' or the host in the SERVER_NAME config variableif present.

    -

    port – the port of the webserver. Defaults to 5000 or theport defined in the SERVER_NAME config variable if present.

    -

    debug – if given, enable or disable debug mode. Seedebug.

    -

    load_dotenv – Load the nearest .env and .flaskenvfiles to set environment variables. Will also change the workingdirectory to the directory containing the first file found.

    -

    options – the options to be forwarded to the underlying Werkzeugserver. See werkzeug.serving.run_simple() for moreinformation.Changelog

    Changed in version 1.0: If installed, python-dotenv will be used to load environmentvariables from .env and .flaskenv files.

    If set, the FLASK_ENV and FLASK_DEBUGenvironment variables will override env anddebug.

    Threaded mode is enabled by default.

    Changed in version 0.10: The default port is now picked from the SERVER_NAMEvariable.

    • savesession(_session, response)
    • Saves the session if it needs updates. For the defaultimplementation, check open_session(). Instead of overriding thismethod we recommend replacing the session_interface.

    • Parameters

    • secret_key
    • If a secret key is set, cryptographic components can use this tosign cookies and other things. Set this to a complex random valuewhen you want to use the secure cookie for instance.

    This attribute can also be configured from the config with theSECRET_KEY configuration key. Defaults to None.

    • selectjinja_autoescape(_filename)
    • Returns True if autoescaping should be active for the giventemplate name. If no template name is given, returns True.Changelog

    New in version 0.5.

    • send_file_max_age_default
    • A timedelta which is used as default cache_timeoutfor the send_file() functions. The default is 12 hours.

    This attribute can also be configured from the config with theSEND_FILE_MAX_AGE_DEFAULT configuration key. This configurationvariable can also be set with an integer value used as seconds.Defaults to timedelta(hours=12)

    • sendstatic_file(_filename)
    • Function used internally to send static files from the staticfolder to the browser.Changelog

    New in version 0.5.

    • session_cookie_name
    • The secure cookie uses this for the name of the session cookie.

    This attribute can also be configured from the config with theSESSION_COOKIE_NAME configuration key. Defaults to 'session'

    • sessioninterface = _
    • the session interface to use. By default an instance of[SecureCookieSessionInterface](/read/flask-v1.1.x/e39

(本文超出单文档体积上限,已截断)