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()`](#flask.Flask.open_resource).

Usually you create a [`Flask`](#flask.Flask) instance in your main module orin the `init.py` file of your package like this:




```
1. from flask import Flask
   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.py`you should create it with one of the two versions below:




```
1. app = Flask('yourapplication')
   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 not*yourapplication.views.frontend*)

Changelog

New in version 1.0: The `hostmatching` *and `static_host` parameters were added.



New in version 1.0: The `subdomain_matching` parameter was added. Subdomainmatching needs to be enabled manually now. Setting[`SERVER_NAME`](https://dormousehole.readthedocs.io/en/latest/config.html#SERVER_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 to[SERVER\_NAME](https://dormousehole.readthedocs.io/en/latest/config.html#SERVER_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.*

*`add_template_filter`(\_f*, *name=None*)[¶](#flask.Flask.add_template_filter)
:   Register a custom template filter. Works exactly like the[`template_filter()`](#flask.Flask.template_filter) decorator.

    |Parameters:
    |——-
    |**name** – the optional name of the filter, otherwise thefunction name will be used.

`addtemplate_global`*(\_f*, *name=None*)[¶](#flask.Flask.add_template_global)
:   Register a custom template global function. Works exactly like the[`template_global()`](#flask.Flask.template_global) decorator.
    Changelog

    New in version 0.10.


    |Parameters:
    |——-
    |**name** – the optional name of the global function, otherwise thefunction name will be used.

`addtemplate_test`*(\_f*, *name=None*)[¶](#flask.Flask.add_template_test)
:   Register a custom template test. Works exactly like the[`template_test()`](#flask.Flask.template_test) decorator.
    Changelog

    New in version 0.10.


    |Parameters:
    |——-
    |**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*)[¶](#flask.Flask.add_url_rule)
:   Connects a URL rule. Works exactly like the [`route()`](#flask.Flask.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():
           pass
       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()`](#flask.Flask.route) invokes [`add_url_rule()`](#flask.Flask.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](#url-route-registrations).**Changelog

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



    Changed in version 0.2: \_view\_func* parameter added.


    |Parameters:
    |——-
    |
    - **rule** – the URL rule as string
    - **endpoint** – the endpoint for the registered URL rule. Flaskitself assumes the name of the view function asendpoint
    - **view\_func** – the function to call when serving a request to theprovided endpoint
    - **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.
    - **options** – the options to be forwarded to the underlying[Rule](http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule) 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.*

*`after_request`(\_f*)[¶](#flask.Flask.after_request)
:   Register a function to be run after each request.

    Your function must take one parameter, an instance of[`response_class`](#flask.Flask.response_class) and return a new response object or thesame (see [`process_response()`](#flask.Flask.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*[¶](#flask.Flask.after_request_funcs)*
:   *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()`](#flask.Flask.after_request) decorator.*

*`app_context`()[¶](#flask.Flask.app_context)*
:   *Create an [`AppContext`](#flask.ctx.AppContext). Use as a `with`block to push the context, which will make [`current_app`](#flask.current_app)point at this application.

    An application context is automatically pushed by[`RequestContext.push()`](#flask.ctx.RequestContext.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():
           init_db()
    ```





    See [应用情境](/read/flask-10/25.md).
    Changelog

    New in version 0.9.*

*`app_ctx_globals_class`[¶](#flask.Flask.app_ctx_globals_class)*
:   *alias of [`flask.ctx._AppCtxGlobals`](#flask.ctx._AppCtxGlobals)*

*`auto_find_instance_path`()[¶](#flask.Flask.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.*

*`before_first_request`(\_f*)[¶](#flask.Flask.before_first_request)
:   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*[¶](#flask.Flask.before_first_request_funcs)*
:   *A list of functions that will be called at the beginning of thefirst request to this instance. To register a function, use the[`before_first_request()`](#flask.Flask.before_first_request) decorator.
    Changelog

    New in version 0.8.*

*`before_request`(\_f*)[¶](#flask.Flask.before_request)
:   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*[¶](#flask.Flask.before_request_funcs)*
:   *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()`](#flask.Flask.before_request)decorator.*

*`blueprints`* = None*[¶](#flask.Flask.blueprints)*
:   *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.*

*`cli`* = None*[¶](#flask.Flask.cli)*
:   *The click command line context for this application. Commandsregistered here show up in the **flask** command once theapplication has been discovered. The default commands areprovided by Flask itself and can be overridden.

    This is an instance of a [`click.Group`](http://click.pocoo.org/api/#click.Group) object.*

*`config`* = None*[¶](#flask.Flask.config)*
:   *The configuration dictionary as [`Config`](#flask.Config). This behavesexactly like a regular dictionary but supports additional methodsto load a config from files.*

*`config_class`[¶](#flask.Flask.config_class)*
:   *alias of `flask.config.Config`*

*`context_processor`(\_f*)[¶](#flask.Flask.context_processor)
:   Registers a template context processor function.

`createglobal_jinja_loader`*()[¶](#flask.Flask.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()`](#flask.Flask.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`()[¶](#flask.Flask.create_jinja_environment)*
:   *Creates the Jinja2 environment based on [`jinja_options`](#flask.Flask.jinja_options)and [`select_jinja_autoescape()`](#flask.Flask.select_jinja_autoescape). Since 0.7 this also addsthe Jinja2 globals and filters after initialization. Overridethis function to customize the behavior.
    Changelog

    Changed in version 0.11: `Environment.auto_reload` set in accordance with`TEMPLATES_AUTO_RELOAD` configuration option.



    New in version 0.5.*

*`create_url_adapter`(\_request*)[¶](#flask.Flask.create_url_adapter)
:   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`](https://dormousehole.readthedocs.io/en/latest/config.html#SERVER_NAME) no longer implicitly enables subdomainmatching. Use `subdomainmatching` *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.*

*`debug`[¶](#flask.Flask.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`](https://dormousehole.readthedocs.io/en/latest/config.html#DEBUG) config key. This isenabled when [`env`](#flask.Flask.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`](#flask.Flask.env) is `'development'`, or`False` otherwise.*

*`default_config`* = {'APPLICATION*ROOT': '/', '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(31), 'PREFERRED\_URL\_SCHEME': 'http', 'PRESERVE\_CONTEXT\_ON\_EXCEPTION': None, 'PROPAGATE\_EXCEPTIONS': None, 'SECRET\_KEY': None, 'SEND\_FILE\_MAX\_AGE\_DEFAULT': datetime.timedelta(0, 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}*[¶](#flask.Flask.default_config)
:   Default configuration parameters.

`dispatchrequest`*()[¶](#flask.Flask.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()`](#flask.make_response).
    Changelog

    Changed in version 0.7: This no longer does the exception handling, this code wasmoved to the new [`full_dispatch_request()`](#flask.Flask.full_dispatch_request).*

*`do_teardown_appcontext`(\_exc=<object object>*)[¶](#flask.Flask.do_teardown_appcontext)
:   Called right before the application context is popped.

    When handling a request, the application context is poppedafter the request context. See [`do_teardown_request()`](#flask.Flask.do_teardown_request).

    This calls all functions decorated with[`teardown_appcontext()`](#flask.Flask.teardown_appcontext). Then the[`appcontext_tearing_down`](#flask.appcontext_tearing_down) signal is sent.

    This is called by[`AppContext.pop()`](#flask.ctx.AppContext.pop).
    Changelog

    New in version 0.9.

`doteardown_request`*(\_exc=<object object>*)[¶](#flask.Flask.do_teardown_request)
:   Called after the request is dispatched and the response isreturned, right before the request context is popped.

    This calls all functions decorated with[`teardown_request()`](#flask.Flask.teardown_request), and [`Blueprint.teardown_request()`](#flask.Blueprint.teardown_request)if a blueprint handled the request. Finally, the[`request_tearing_down`](#flask.request_tearing_down) signal is sent.

    This is called by[`RequestContext.pop()`](#flask.ctx.RequestContext.pop),which may be delayed during testing to maintain access toresources.

    |Parameters:
    |——-
    |**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*)[¶](#flask.Flask.endpoint)
:   A decorator to register a function as an endpoint.Example:




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





    |Parameters:
    |——-
    |**endpoint** – the name of the endpoint

`env`[¶](#flask.Flask.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`](https://dormousehole.readthedocs.io/en/latest/config.html#ENV) config key. This is set by the`FLASKENV` *environment variable and may not behave asexpected if set in code.

    **Do not enable development when deploying in production.**

    Default: `'production'`*

*`error_handler_spec`* = None*[¶](#flask.Flask.error_handler_spec)*
:   *A dictionary of all registered error handlers. The key is `None`for 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()`](#flask.Flask.errorhandler)decorator.*

*`errorhandler`(\_code\_or\_exception*)[¶](#flask.Flask.errorhandler)
:   Register a function to handle errors by code or exception class.

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




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

     *You can also register handlers for arbitrary exceptions:




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




    Changelog

    New in version 0.7: Use [`register_error_handler()`](#flask.Flask.register_error_handler) instead of modifying[`error_handler_spec`](#flask.Flask.error_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 the[`HTTPException`](http://werkzeug.pocoo.org/docs/exceptions/#werkzeug.exceptions.HTTPException) class.


    |Parameters:
    |——-
    |**code\_or\_exception** – the code as integer for the handler, oran arbitrary exception*

*`extensions`* = None*[¶](#flask.Flask.extensions)*
:   *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:




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

`fulldispatch_request`*()[¶](#flask.Flask.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.*

*`get_send_file_max_age`(\_filename*)[¶](#flask.Flask.get_send_file_max_age)
:   Provides default cache*timeout for the [`send_file()`](#flask.send_file) functions.

    By default, this function returns `SEND_FILE_MAX_AGE_DEFAULT` fromthe configuration of [`current_app`](#flask.current_app).

    Static file functions such as [`send_from_directory()`](#flask.send_from_directory) use thisfunction, and [`send_file()`](#flask.send_file) calls this function on[`current_app`](#flask.current_app) when the given cache\_timeout is `None`. If acache\_timeout is given in [`send_file()`](#flask.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:




    ```
    1. 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.*

*`got_first_request`[¶](#flask.Flask.got_first_request)*
:   *This attribute is set to `True` if the application startedhandling the first request.
    Changelog

    New in version 0.8.*

*`handle_exception`(\_e*)[¶](#flask.Flask.handle_exception)
:   Default exception handling that kicks in when an exceptionoccurs that is not caught. In debug mode the exception willbe re-raised immediately, otherwise it is logged and the handlerfor a 500 internal server error is used. If no such handlerexists, a default 500 internal server error message is displayed.
    Changelog

    New in version 0.3.

`handlehttp_exception`*(\_e*)[¶](#flask.Flask.handle_http_exception)
:   Handles an HTTP exception. By default this will invoke theregistered error handlers and fall back to returning theexception as response.
    Changelog

    New in version 0.3.

`handleurl_build_error`*(\_error*, *endpoint*, *values*)[¶](#flask.Flask.handle_url_build_error)
:   Handle `BuildError` on [`url_for()`](#flask.url_for).

`handleuser_exception`*(\_e*)[¶](#flask.Flask.handle_user_exception)
:   This method is called whenever an exception occurs that should behandled. A special case are`HTTPException`s which are forwarded bythis function to the [`handle_http_exception()`](#flask.Flask.handle_http_exception) method. Thisfunction will either return a response value or reraise theexception with the same traceback.
    Changelog

    Changed in version 1.0: Key errors raised from request data like `form` show the the badkey in debug mode rather than a generic bad request message.



    New in version 0.7.

`hasstatic_folder`*[¶](#flask.Flask.has_static_folder)*
:   *This is `True` if the package bound object’s container has afolder for static files.
    Changelog

    New in version 0.5.*

*`import_name`* = None*[¶](#flask.Flask.import_name)*
:   *The name of the package or module that this app belongs to. Do notchange this once it is set by the constructor.*

*`inject_url_defaults`(\_endpoint*, *values*)[¶](#flask.Flask.inject_url_defaults)
:   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*[¶](#flask.Flask.instance_path)*
:   *Holds the path to the instance folder.
    Changelog

    New in version 0.8.*

*`iter_blueprints`()[¶](#flask.Flask.iter_blueprints)*
:   *Iterates over all blueprints by the order they were registered.
    Changelog

    New in version 0.11.*

*`jinja_env`[¶](#flask.Flask.jinja_env)*
:   *The Jinja2 environment used to load templates.*

*`jinja_environment`[¶](#flask.Flask.jinja_environment)*
:   *alias of `flask.templating.Environment`*

*`jinja_loader`[¶](#flask.Flask.jinja_loader)*
:   *The Jinja loader for this package bound object.
    Changelog

    New in version 0.5.*

*`jinja_options`* = {'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with*']}*[¶](#flask.Flask.jinja_options)
:   Options that are passed directly to the Jinja2 environment.

`jsondecoder`*[¶](#flask.Flask.json_decoder)*
:   *alias of [`flask.json.JSONDecoder`](#flask.json.JSONDecoder)*

*`json_encoder`[¶](#flask.Flask.json_encoder)*
:   *alias of [`flask.json.JSONEncoder`](#flask.json.JSONEncoder)*

*`log_exception`(\_exc\_info*)[¶](#flask.Flask.log_exception)
:   Logs an exception. This is called by [`handle_exception()`](#flask.Flask.handle_exception)if debugging is disabled and right before the handler is called.The default implementation logs the exception as error on the[`logger`](#flask.Flask.logger).
    Changelog

    New in version 0.8.

`logger`[¶](#flask.Flask.logger)
:   The `'flask.app'` logger, a standard Python[`Logger`](https://docs.python.org/3/library/logging.html#logging.Logger).

    In debug mode, the logger’s `level` will be setto `DEBUG`.

    If there are no handlers configured, a default handler will be added.See [日志](https://dormousehole.readthedocs.io/en/latest/logging.html#logging) for more information.
    Changelog

    Changed in version 1.0: Behavior was simplified. The logger is always named`flask.app`. The level is only set during configuration, itdoesn’t check `app.debug` each time. Only one format is used,not different ones depending on `app.debug`. No handlers areremoved, and a handler is only added if no handlers are alreadyconfigured.



    New in version 0.3.

`makeconfig`*(\_instance\_relative=False*)[¶](#flask.Flask.make_config)
:   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.

`makedefault_options_response`*()[¶](#flask.Flask.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`()[¶](#flask.Flask.make_null_session)*
:   *Creates a new instance of a missing session. Instead of overridingthis method we recommend replacing the [`session_interface`](#flask.Flask.session_interface).
    Changelog

    New in version 0.7.*

*`make_response`(\_rv*)[¶](#flask.Flask.make_response)
:   Convert the return value from a view function to an instance of[`response_class`](#flask.Flask.response_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`:

    `str` (`unicode` in Python 2)
    :   A response object is created with the string encoded to UTF-8as the body.

    `bytes` (`str` in Python 2)
    :   A response object is created with the bytes as the body.

    `tuple`
    :   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, and`headers` is a dictionary or a list of `(key, value)`tuples. If `body` is a [`response_class`](#flask.Flask.response_class) instance,`status` overwrites the exiting value and `headers` areextended.

    [`response_class`](#flask.Flask.response_class)
    :   The object is returned unchanged.

    other [`Response`](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.Response) class
    :   The object is coerced to [`response_class`](#flask.Flask.response_class).

    [`callable()`](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.

`makeshell_context`*()[¶](#flask.Flask.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`[¶](#flask.Flask.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.*

*`open_instance_resource`(\_resource*, *mode='rb'*)[¶](#flask.Flask.open_instance_resource)
:   Opens a resource from the application’s instance folder([`instance_path`](#flask.Flask.instance_path)). Otherwise works like[`open_resource()`](#flask.Flask.open_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'*)[¶](#flask.Flask.open_resource)
:   Opens a resource from the application’s resource folder. To seehow this works, consider the following folder structure:




    ```
    1. /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:




    ```
    1. with app.openresource('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** – resource file opening mode, default is ‘rb’.*

*`open_session`(\_request*)[¶](#flask.Flask.open_session)
:   Creates or opens a new session. Default implementation stores allsession data in a signed cookie. This requires that the[`secret_key`](#flask.Flask.secret_key) is set. Instead of overriding this methodwe recommend replacing the [`session_interface`](#flask.Flask.session_interface).

    |Parameters:
    |——-
    |**request** – an instance of [`request_class`](#flask.Flask.request_class).

`permanentsession_lifetime`*[¶](#flask.Flask.permanent_session_lifetime)*
:   *A [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.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 the`PERMANENT_SESSION_LIFETIME` configuration key. Defaults to`timedelta(days=31)`*

*`preprocess_request`()[¶](#flask.Flask.preprocess_request)*
:   *Called before the request is dispatched. Calls[`url_value_preprocessors`](#flask.Flask.url_value_preprocessors) registered with the app and thecurrent blueprint (if any). Then calls [`before_request_funcs`](#flask.Flask.before_request_funcs)registered with the app and the blueprint.

    If any [`before_request()`](#flask.Flask.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.*

*`preserve_context_on_exception`[¶](#flask.Flask.preserve_context_on_exception)*
:   *Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`configuration value in case it’s set, otherwise a sensible defaultis returned.
    Changelog

    New in version 0.7.*

*`process_response`(\_response*)[¶](#flask.Flask.process_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()`](#flask.Flask.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`](#flask.Flask.response_class) object.
    |Returns:
    |——-
    |a new response object or the same, has to be aninstance of [`response_class`](#flask.Flask.response_class).

`propagateexceptions`*[¶](#flask.Flask.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.*

*`register_blueprint`(\_blueprint*, *\*\*options*)[¶](#flask.Flask.register_blueprint)
:   Register a [`Blueprint`](#flask.Blueprint) on the application. Keywordarguments passed to this method will override the defaults set on theblueprint.

    Calls the blueprint’s [`register()`](#flask.Blueprint.register) method afterrecording the blueprint in the application’s [`blueprints`](#flask.Flask.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 to[BlueprintSetupState](#flask.blueprints.BlueprintSetupState). They can beaccessed in [record()](#flask.Blueprint.record) callbacks.

    Changelog

    New in version 0.7.

`registererror_handler`*(\_code\_or\_exception*, *f*)[¶](#flask.Flask.register_error_handler)
:   Alternative error attach function to the [`errorhandler()`](#flask.Flask.errorhandler)decorator that is more straightforward to use for non decoratorusage.
    Changelog

    New in version 0.7.

`requestclass`*[¶](#flask.Flask.request_class)*
:   *alias of `flask.wrappers.Request`*

*`request_context`(\_environ*)[¶](#flask.Flask.request_context)
:   Create a [`RequestContext`](#flask.ctx.RequestContext) representing aWSGI environment. Use a `with` block to push the context,which will make [`request`](#flask.request) point at this request.

    See [请求情境](/read/flask-10/26.md).

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

    |Parameters:
    |——-
    |**environ** – a WSGI environment

`responseclass`*[¶](#flask.Flask.response_class)*
:   *alias of `flask.wrappers.Response`*

*`root_path`* = None*[¶](#flask.Flask.root_path)*
:   *Absolute path to the package on the filesystem. Used to look upresources contained in the package.*

*`route`(\_rule*, *\*\*options*)[¶](#flask.Flask.route)
:   A decorator that is used to register a view function for agiven URL rule. This does the same thing as [`add_url_rule()`](#flask.Flask.add_url_rule)but is intended for decorator usage:




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





    For more information refer to [URL Route Registrations](#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 underlying[Rule](http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule) 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*)[¶](#flask.Flask.run)
:   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 [部署方式](https://dormousehole.readthedocs.io/en/latest/deploying/index.html#deployment) for WSGI server recommendations.

    If the [`debug`](#flask.Flask.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 pass`useevalex=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()`](#flask.Flask.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. See[debug](#flask.Flask.debug).
    - **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()](http://werkzeug.pocoo.org/docs/serving/#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_DEBUG`environment variables will override [`env`](#flask.Flask.env) and[`debug`](#flask.Flask.debug).

    Threaded mode is enabled by default.



    Changed in version 0.10: The default port is now picked from the `SERVER_NAME`variable.*

*`save_session`(\_session*, *response*)[¶](#flask.Flask.save_session)
:   Saves the session if it needs updates. For the defaultimplementation, check [`open_session()`](#flask.Flask.open_session). Instead of overriding thismethod we recommend replacing the [`session_interface`](#flask.Flask.session_interface).

    |Parameters:
    |——-
    |
    - **session** – the session to be saved (a[SecureCookie](http://werkzeug.pocoo.org/docs/contrib/securecookie/#werkzeug.contrib.securecookie.SecureCookie)object)
    - **response** – an instance of [response\_class](#flask.Flask.response_class)

`secretkey`*[¶](#flask.Flask.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 the[`SECRET_KEY`](https://dormousehole.readthedocs.io/en/latest/config.html#SECRET_KEY) configuration key. Defaults to `None`.*

*`select_jinja_autoescape`(\_filename*)[¶](#flask.Flask.select_jinja_autoescape)
:   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.

`sendfile_max_age_default`*[¶](#flask.Flask.send_file_max_age_default)*
:   *A [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) which is used as default cache\_timeoutfor the [`send_file()`](#flask.send_file) functions. The default is 12 hours.

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

*`send_static_file`(\_filename*)[¶](#flask.Flask.send_static_file)
:   Function used internally to send static files from the staticfolder to the browser.
    Changelog

    New in version 0.5.

`sessioncookie_name`*[¶](#flask.Flask.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 the`SESSION_COOKIE_NAME` configuration key. Defaults to `'session'`*

*`session_interface`* = <flask.sessions.SecureCookieSessionInterface object>*[¶](#flask.Flask.session_interface)*
:   *the session interface to use. By default an instance of[`SecureCookieSessionInterface`](#flask.sessions.SecureCookieSessionInterface) is used here.
    Changelog

    New in version 0.8.*

*`shell_context_processor`(\_f*)[¶](#flask.Flask.shell_context_processor)
:   Registers a shell context processor function.
    Changelog

    New in version 0.11.

`shellcontext_processors` = None*[¶](#flask.Flask.shell_context_processors)*
:   *A list of shell context processor functions that should be runwhen a shell context is created.
    Changelog

    New in version 0.11.*

*`should_ignore_error`(\_error*)[¶](#flask.Flask.should_ignore_error)
:   This is called to figure out if an error should be ignoredor not as far as the teardown system is concerned. If thisfunction returns `True` then the teardown handlers will not bepassed the error.
    Changelog

    New in version 0.10.

`staticfolder`*[¶](#flask.Flask.static_folder)*
:   *The absolute path to the configured static folder.*

*`s

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