### 導航
- [索引](# "總目錄")
- [下一頁](# "Flask 中的設計決策") |
- [上一頁](# "聚沙成塔") |
- [Flask 0.10.1 文檔](#) ?
# API
這部分文檔涵蓋了 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*)
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:
~~~
from flask import Flask
app = Flask(__name__)
~~~
About the First Parameter
The idea of the first parameter is to give Flask an idea whatbelongs to your application. This name is used to find resourceson the file system, 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:
~~~
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 notyourapplication.views.frontend)
0.7 新版功能: The static_url_path, static_folder, and template_folderparameters were added.
0.8 新版功能: The instance_path and instance_relative_config parameters wereadded.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>import_name</strong> – the name of the application package</li><li><strong>static_url_path</strong> – can be used to specify a different path for thestatic files on the web. Defaults to the nameof the <cite>static_folder</cite> folder.</li><li><strong>static_folder</strong> – the folder with static files that should be servedat <cite>static_url_path</cite>. Defaults to the <tt class="docutils literal"><span class="pre">'static'</span></tt>folder in the root path of the application.</li><li><strong>template_folder</strong> – the folder that contains the templates that shouldbe used by the application. Defaults to<tt class="docutils literal"><span class="pre">'templates'</span></tt> folder in the root path of theapplication.</li><li><strong>instance_path</strong> – An alternative instance path for the application.By default the folder <tt class="docutils literal"><span class="pre">'instance'</span></tt> next to thepackage or module is assumed to be the instancepath.</li><li><strong>instance_relative_config</strong> – if set to <cite>True</cite> relative filenamesfor loading the config are assumed tobe relative to the instance path insteadof the application root.</li></ul></td></tr></tbody></table>
add_template_filter(**args*, ***kwargs*)
Register a custom template filter. Works exactly like the[template_filter()](# "flask.Flask.template_filter") decorator.
| 參數: | **name** – the optional name of the filter, otherwise thefunction name will be used. |
|-----|-----|
add_template_global(**args*, ***kwargs*)
Register a custom template global function. Works exactly like the[template_global()](# "flask.Flask.template_global") decorator.
0.10 新版功能.
| 參數: | **name** – the optional name of the global function, otherwise thefunction name will be used. |
|-----|-----|
add_template_test(**args*, ***kwargs*)
Register a custom template test. Works exactly like the[template_test()](# "flask.Flask.template_test") decorator.
0.10 新版功能.
| 參數: | **name** – the optional name of the test, otherwise thefunction name will be used. |
|-----|-----|
add_url_rule(**args*, ***kwargs*)
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:
~~~
@app.route('/')
def index():
pass
~~~
Is equivalent to the following:
~~~
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:
~~~
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 路由注冊*](#).
在 0.2 版更改: view_func parameter added.
在 0.6 版更改: OPTIONS is added automatically as method.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>rule</strong> – the URL rule as string</li><li><strong>endpoint</strong> – the endpoint for the registered URL rule. Flaskitself assumes the name of the view function asendpoint</li><li><strong>view_func</strong> – the function to call when serving a request to theprovided endpoint</li><li><strong>options</strong> – the options to be forwarded to the underlying<a class="reference external" href="http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule" title="(在 Werkzeug v0.10)"><tt class="xref py py-class docutils literal"><span class="pre">Rule</span></tt></a><span class="link-target"> [http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule]</span> object. A changeto Werkzeug is handling of method options. methodsis a list of methods this rule should be limitedto (<cite>GET</cite>, <cite>POST</cite> etc.). By default a rulejust listens for <cite>GET</cite> (and implicitly <cite>HEAD</cite>).Starting with Flask 0.6, <cite>OPTIONS</cite> is implicitlyadded and handled by the standard request handling.</li></ul></td></tr></tbody></table>
after_request(**args*, ***kwargs*)
Register a function to be run after each request. Your functionmust take one parameter, a [response_class](# "flask.Flask.response_class") object and returna new response object or the same (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.
after_request_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 open database connections or getting hold of thecurrently logged in user. To register a function here, use the[after_request()](# "flask.Flask.after_request") decorator.
app_context()
Binds the application only. For as long as the application is boundto the current context the [flask.current_app](# "flask.current_app") points to thatapplication. An application context is automatically created when arequest context is pushed if necessary.
Example usage:
~~~
with app.app_context():
...
~~~
0.9 新版功能.
app_ctx_globals_class
The class that is used for the [g](# "flask.g") instance.
Example use cases for a custom class:
1. Store arbitrary attributes on flask.g.
1. Add a property for lazy per-request database connectors.
1. Return None instead of AttributeError on expected attributes.
1. Raise exception if an unexpected attr is set, a “controlled” flask.g.
In Flask 0.9 this property was called request_globals_class but itwas changed in 0.10 to [app_ctx_globals_class](# "flask.Flask.app_ctx_globals_class") because theflask.g object is not application context scoped.
0.10 新版功能.
_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.
0.8 新版功能.
before_first_request(**args*, ***kwargs*)
Registers a function to be run before the first request to thisinstance of the application.
0.8 新版功能.
before_first_request_funcs* = None*
A lists of functions that should be called at the beginning of thefirst request to this instance. To register a function here, usethe [before_first_request()](# "flask.Flask.before_first_request") decorator.
0.8 新版功能.
before_request(**args*, ***kwargs*)
Registers a function to run before each request.
before_request_funcs* = None*
A dictionary with lists of functions that should be called at thebeginning of the request. The key of the dictionary is the name ofthe blueprint this function is active for, None for all requests.This can for example be used to open database connections orgetting hold of the currently logged in user. To register afunction here, use the [before_request()](# "flask.Flask.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.
0.7 新版功能.
config* = None*
The configuration dictionary as [Config](# "flask.Config"). This behavesexactly like a regular dictionary but supports additional methodsto load a config from files.
context_processor(**args*, ***kwargs*)
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()](# "flask.Flask.jinja_loader") function instead.
The global loader dispatches between the loaders of the applicationand the individual blueprints.
0.7 新版功能.
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.
0.5 新版功能.
create_url_adapter(*request*)
Creates a URL adapter for the given request. The URL adapteris created at a point where the request context is not yet set upso the request is passed explicitly.
0.6 新版功能.
在 0.9 版更改: This can now also be called without a request object when theURL adapter is created for the application context.
debug
The debug flag. Set this to True to enable debugging of theapplication. In debug mode the debugger will kick in when an unhandledexception occurs and the integrated server will automatically reloadthe application if changes in the code are detected.
This attribute can also be configured from the config with the DEBUGconfiguration key. Defaults to False.
debug_log_format* = '--------------------------------------------------------------------------------\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s\n--------------------------------------------------------------------------------'*
The logging format used for the debug logger. This is only used whenthe application is in debug mode, otherwise the attached logginghandler does the formatting.
0.3 新版功能.
default_config* = ImmutableDict({'JSON_AS_ASCII': True, 'USE_X_SENDFILE': False, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_NAME': 'session', 'LOGGER_NAME': None, 'DEBUG': False, 'SECRET_KEY': None, 'MAX_CONTENT_LENGTH': None, 'APPLICATION_ROOT': None, 'SERVER_NAME': None, 'PREFERRED_URL_SCHEME': 'http', 'JSONIFY_PRETTYPRINT_REGULAR': True, 'TESTING': False, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'PROPAGATE_EXCEPTIONS': None, 'TRAP_BAD_REQUEST_ERRORS': False, 'JSON_SORT_KEYS': True, 'SESSION_COOKIE_HTTPONLY': True, 'SEND_FILE_MAX_AGE_DEFAULT': 43200, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SESSION_COOKIE_SECURE': False, 'TRAP_HTTP_EXCEPTIONS': 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()](# "flask.make_response").
在 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=None*)
Called when an application context is popped. This works prettymuch the same as [do_teardown_request()](# "flask.Flask.do_teardown_request") but for the applicationcontext.
0.9 新版功能.
do_teardown_request(*exc=None*)
Called after the actual request dispatching and willcall every as [teardown_request()](# "flask.Flask.teardown_request") decorated function. This isnot actually called by the [Flask](# "flask.Flask") object itself but is alwaystriggered when the request context is popped. That way we have atighter control over certain resources under testing environments.
在 0.9 版更改: Added the exc argument. Previously this was always using thecurrent exception information.
enable_modules* = True*
Enable the deprecated module support? This is active by defaultin 0.7 but will be changed to False in 0.8. With Flask 1.0 moduleswill be removed in favor of Blueprints
endpoint(**args*, ***kwargs*)
A decorator to register a function as an endpoint.Example:
~~~
@app.endpoint('example.endpoint')
def example():
return "example"
~~~
| 參數: | **endpoint** – the name of the endpoint |
|-----|-----|
error_handler_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 they 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 a error handler, use the [errorhandler()](# "flask.Flask.errorhandler")decorator.
errorhandler(**args*, ***kwargs*)
A decorator that is used to register a function give a givenerror 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
~~~
You can also register a function as error handler without usingthe [errorhandler()](# "flask.Flask.errorhandler") decorator. The following example isequivalent to the one above:
~~~
def page_not_found(error):
return 'This page does not exist', 404
app.error_handler_spec[None][404] = page_not_found
~~~
Setting error handlers via assignments to [error_handler_spec](# "flask.Flask.error_handler_spec")however is discouraged as it requires fiddling with nested dictionariesand the special case for arbitrary exception types.
The first None refers to the active blueprint. If the errorhandler should be application wide None shall be used.
0.7 新版功能: One can now additionally also register custom exception typesthat do not necessarily have to be a subclass of theHTTPException class.
| 參數: | **code** – the code as integer for the handler |
|-----|-----|
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 flaskext module. For example incase of a “Flask-Foo” extension in flaskext.foo, the key would be'foo'.
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.
0.7 新版功能.
get_send_file_max_age(*filename*)
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:
~~~
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)
~~~
0.9 新版功能.
got_first_request
This attribute is set to True if the application startedhandling the first request.
0.8 新版功能.
handle_exception(*e*)
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.
0.3 新版功能.
handle_http_exception(*e*)
Handles an HTTP exception. By default this will invoke theregistered error handlers and fall back to returning theexception as response.
0.3 新版功能.
handle_url_build_error(*error*, *endpoint*, *values*)
Handle BuildError on [url_for()](# "flask.url_for").
handle_user_exception(*e*)
This method is called whenever an exception occurs that should behandled. A special case areHTTPExceptions 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.
0.7 新版功能.
has_static_folder
This is True if the package bound object's container has afolder named 'static'.
0.5 新版功能.
init_jinja_globals()
Deprecated. Used to initialize the Jinja2 globals.
0.5 新版功能.
在 0.7 版更改: This method is deprecated with 0.7. Override[create_jinja_environment()](# "flask.Flask.create_jinja_environment") instead.
inject_url_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.
0.7 新版功能.
instance_path* = None*
Holds the path to the instance folder.
0.8 新版功能.
jinja_env
The Jinja2 environment used to load templates.
jinja_loader
The Jinja loader for this package bound object.
0.5 新版功能.
jinja_options* = ImmutableDict({'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']})*
Options that are passed directly to the Jinja2 environment.
json_decoder
The JSON decoder class to use. Defaults to [JSONDecoder](# "flask.json.JSONDecoder").
0.10 新版功能.
JSONDecoder 的別名
json_encoder
The JSON encoder class to use. Defaults to [JSONEncoder](# "flask.json.JSONEncoder").
0.10 新版功能.
JSONEncoder 的別名
log_exception(*exc_info*)
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").
0.8 新版功能.
logger
A [logging.Logger](http://docs.python.org/dev/library/logging.html#logging.Logger "(在 Python v3.5)") [http://docs.python.org/dev/library/logging.html#logging.Logger] object for this application. Thedefault configuration is to log to stderr if the application isin debug mode. This logger can be used to (surprise) log messages.Here some examples:
~~~
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
~~~
0.3 新版功能.
logger_name
The name of the logger to use. By default the logger name is thepackage name passed to the constructor.
0.4 新版功能.
make_config(*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.
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.
0.7 新版功能.
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").
0.7 新版功能.
make_response(*rv*)
Converts the return value from a view function to a realresponse object that is an instance of [response_class](# "flask.Flask.response_class").
The following types are allowed for rv:
| [response_class](# "flask.Flask.response_class") | the object is returned unchanged |
|-----|-----|
| [str](http://docs.python.org/dev/library/stdtypes.html#str "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#str] | a response object is created with thestring as body |
| unicode | a response object is created with thestring encoded to utf-8 as body |
| a WSGI function | the function is called as WSGI applicationand buffered as response object |
| [tuple](http://docs.python.org/dev/library/stdtypes.html#tuple "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#tuple] | A tuple in the form (response,status,headers) where response is any of thetypes defined here, status is a stringor an integer and headers is a list ofa dictionary with header values. |
| 參數: | **rv** – the return value from the view function |
|-----|-----|
在 0.9 版更改: Previously a tuple was interpreted as the arguments for theresponse object.
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.
0.8 新版功能.
open_instance_resource(*resource*, *mode='rb'*)
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.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>resource</strong> – the name of the resource. To access resources withinsubfolders use forward slashes as separator.</li><li><strong>mode</strong> – resource file opening mode, default is ‘rb'.</li></ul></td></tr></tbody></table>
open_resource(*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)
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>resource</strong> – the name of the resource. To access resources withinsubfolders use forward slashes as separator.</li><li><strong>mode</strong> – resource file opening mode, default is ‘rb'.</li></ul></td></tr></tbody></table>
open_session(*request*)
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").
| 參數: | **request** – an instance of [request_class](# "flask.Flask.request_class"). |
|-----|-----|
permanent_session_lifetime
A [timedelta](http://docs.python.org/dev/library/datetime.html#datetime.timedelta "(在 Python v3.5)") [http://docs.python.org/dev/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 thePERMANENT_SESSION_LIFETIME configuration key. Defaults totimedelta(days=31)
preprocess_request()
Called before the actual request dispatching and willcall every as [before_request()](# "flask.Flask.before_request") decorated function.If any of these function returns a value it's handled asif it was the return value from the view and furtherrequest handling is stopped.
This also triggers the url_value_processor() functions beforethe actual [before_request()](# "flask.Flask.before_request") functions are called.
preserve_context_on_exception
Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTIONconfiguration value in case it's set, otherwise a sensible defaultis returned.
0.7 新版功能.
process_response(*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.
在 0.5 版更改: As of Flask 0.5 the functions registered for after requestexecution are called in reverse order of registration.
| 參數: | **response** – a [response_class](# "flask.Flask.response_class") object. |
|-----|-----|
| 返回: | a new response object or the same, has to be aninstance of [response_class](# "flask.Flask.response_class"). |
propagate_exceptions
Returns the value of the PROPAGATE_EXCEPTIONS configurationvalue in case it's set, otherwise a sensible default is returned.
0.7 新版功能.
register_blueprint(**args*, ***kwargs*)
Registers a blueprint on the application.
0.7 新版功能.
register_error_handler(*code_or_exception*, *f*)
Alternative error attach function to the [errorhandler()](# "flask.Flask.errorhandler")decorator that is more straightforward to use for non decoratorusage.
0.7 新版功能.
register_module(*module*, ***options*)
Registers a module with this application. The keyword argumentof this function are the same as the ones for the constructor of theModule class and will override the values of the module ifprovided.
在 0.7 版更改: The module system was deprecated in favor for the blueprintsystem.
request_class
The class that is used for request objects. See [Request](# "flask.Request")for more information.
[Request](# "flask.Request") 的別名
request_context(*environ*)
Creates a [RequestContext](# "flask.ctx.RequestContext") from the givenenvironment and binds it to the current context. This must be used incombination with the with statement because the request is only boundto the current context for the duration of the with block.
Example usage:
~~~
with app.request_context(environ):
do_something_with(request)
~~~
The object returned can also be used without the with statementwhich is useful for working in the shell. The example above isdoing exactly the same as this code:
~~~
ctx = app.request_context(environ)
ctx.push()
try:
do_something_with(request)
finally:
ctx.pop()
~~~
在 0.3 版更改: Added support for non-with statement usage and with statementis now passed the ctx object.
| 參數: | **environ** – a WSGI environment |
|-----|-----|
response_class
The class that is used for response objects. See[Response](# "flask.Response") for more information.
[Response](# "flask.Response") 的別名
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()](# "flask.Flask.add_url_rule")but is intended for decorator usage:
~~~
@app.route('/')
def index():
return 'Hello World'
~~~
For more information refer to [*URL 路由注冊*](#).
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>rule</strong> – the URL rule as string</li><li><strong>endpoint</strong> – the endpoint for the registered URL rule. Flaskitself assumes the name of the view function asendpoint</li><li><strong>options</strong> – the options to be forwarded to the underlying<a class="reference external" href="http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule" title="(在 Werkzeug v0.10)"><tt class="xref py py-class docutils literal"><span class="pre">Rule</span></tt></a><span class="link-target"> [http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule]</span> object. A changeto Werkzeug is handling of method options. methodsis a list of methods this rule should be limitedto (<cite>GET</cite>, <cite>POST</cite> etc.). By default a rulejust listens for <cite>GET</cite> (and implicitly <cite>HEAD</cite>).Starting with Flask 0.6, <cite>OPTIONS</cite> is implicitlyadded and handled by the standard request handling.</li></ul></td></tr></tbody></table>
run(*host=None*, *port=None*, *debug=None*, ***options*)
Runs the application on a local development server. 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 passuse_evalex=False as parameter. This will keep the debugger'straceback screen active, but disable code execution.
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.
在 0.10 版更改: The default port is now picked from the SERVER_NAME variable.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>host</strong> – the hostname to listen on. Set this to <tt class="docutils literal"><span class="pre">'0.0.0.0'</span></tt> tohave the server available externally as well. Defaults to<tt class="docutils literal"><span class="pre">'127.0.0.1'</span></tt>.</li><li><strong>port</strong> – the port of the webserver. Defaults to <tt class="docutils literal"><span class="pre">5000</span></tt> or theport defined in the <tt class="docutils literal"><span class="pre">SERVER_NAME</span></tt> config variable ifpresent.</li><li><strong>debug</strong> – if given, enable or disable debug mode.See <a class="reference internal" href="#flask.Flask.debug" title="flask.Flask.debug"><tt class="xref py py-attr docutils literal"><span class="pre">debug</span></tt></a>.</li><li><strong>options</strong> – the options to be forwarded to the underlyingWerkzeug server. See<a class="reference external" href="http://werkzeug.pocoo.org/docs/serving/#werkzeug.serving.run_simple" title="(在 Werkzeug v0.10)"><tt class="xref py py-func docutils literal"><span class="pre">werkzeug.serving.run_simple()</span></tt></a><span class="link-target"> [http://werkzeug.pocoo.org/docs/serving/#werkzeug.serving.run_simple]</span> for moreinformation.</li></ul></td></tr></tbody></table>
save_session(*session*, *response*)
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").
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>session</strong> – the session to be saved (a<a class="reference external" href="http://werkzeug.pocoo.org/docs/contrib/securecookie/#werkzeug.contrib.securecookie.SecureCookie" title="(在 Werkzeug v0.10)"><tt class="xref py py-class docutils literal"><span class="pre">SecureCookie</span></tt></a><span class="link-target"> [http://werkzeug.pocoo.org/docs/contrib/securecookie/#werkzeug.contrib.securecookie.SecureCookie]</span>object)</li><li><strong>response</strong> – an instance of <a class="reference internal" href="#flask.Flask.response_class" title="flask.Flask.response_class"><tt class="xref py py-attr docutils literal"><span class="pre">response_class</span></tt></a></li></ul></td></tr></tbody></table>
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.
select_jinja_autoescape(*filename*)
Returns True if autoescaping should be active for the giventemplate name.
0.5 新版功能.
send_static_file(*filename*)
Function used internally to send static files from the staticfolder to the browser.
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'
session_interface* = <flask.sessions.SecureCookieSessionInterface object at 0x3c9c7d0>*
the session interface to use. By default an instance of[SecureCookieSessionInterface](# "flask.sessions.SecureCookieSessionInterface") is used here.
0.8 新版功能.
should_ignore_error(*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.
0.10 新版功能.
teardown_appcontext(**args*, ***kwargs*)
Registers a function to be called when the application contextends. These functions are typically also called when the requestcontext is popped.
Example:
~~~
ctx = app.app_context()
ctx.push()
...
ctx.pop()
~~~
When ctx.pop() is executed in the above example, the teardownfunctions are called just before the app context moves from thestack of active contexts. This becomes relevant if you are usingsuch constructs in tests.
Since a request context typically also manages an applicationcontext it would also be called when you pop a request context.
When a teardown function was called because of an exception it willbe passed an error object.
0.9 新版功能.
teardown_appcontext_funcs* = None*
A list of functions that are called when the application contextis destroyed. Since the application context is also torn downif the request ends this is the place to store code that disconnectsfrom databases.
0.9 新版功能.
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. These functionsare executed when the request context is popped, even if not anactual request was performed.
Example:
~~~
ctx = app.test_request_context()
ctx.push()
...
ctx.pop()
~~~
When ctx.pop() is executed in the above example, the teardownfunctions are called just before the request context moves from thestack of active contexts. This becomes relevant if you are usingsuch constructs in tests.
Generally teardown functions must take every necessary step to avoidthat they will fail. If they do execute code that might fail theywill have to surround the execution of these code by try/exceptstatements and log occurring errors.
When a teardown function was called because of a exception it willbe passed an error object.
Debug Note
In debug mode Flask will not tear down a request on an exceptionimmediately. Instead if will keep it alive so that the interactivedebugger can still access it. This behavior can be controlledby the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.
teardown_request_funcs* = None*
A dictionary with lists of functions that are called aftereach request, even if an exception has occurred. The key of thedictionary is the name of the blueprint this function is active for,None for all requests. These functions are not allowed to modifythe request, and their return values are ignored. If an exceptionoccurred while processing the request, it gets passed to eachteardown_request function. To register a function here, use the[teardown_request()](# "flask.Flask.teardown_request") decorator.
0.7 新版功能.
template_context_processors* = None*
A dictionary with list of functions that are called without argumentto populate the template context. The key of the dictionary is thename of the blueprint this function is active for, None for allrequests. Each returns a dictionary that the template context isupdated with. To register a function here, use the[context_processor()](# "flask.Flask.context_processor") decorator.
template_filter(**args*, ***kwargs*)
A decorator that is used to register custom template filter.You can specify a name for the filter, otherwise the functionname will be used. Example:
~~~
@app.template_filter()
def reverse(s):
return s[::-1]
~~~
| 參數: | **name** – the optional name of the filter, otherwise thefunction name will be used. |
|-----|-----|
template_global(**args*, ***kwargs*)
A decorator that is used to register a custom template global function.You can specify a name for the global function, otherwise the functionname will be used. Example:
~~~
@app.template_global()
def double(n):
return 2 * n
~~~
0.10 新版功能.
| 參數: | **name** – the optional name of the global function, otherwise thefunction name will be used. |
|-----|-----|
template_test(**args*, ***kwargs*)
A decorator that is used to register custom template test.You can specify a name for the test, otherwise the functionname will be used. Example:
~~~
@app.template_test()
def is_prime(n):
if n == 2:
return True
for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
if n % i == 0:
return False
return True
~~~
0.10 新版功能.
| 參數: | **name** – the optional name of the test, otherwise thefunction name will be used. |
|-----|-----|
test_client(*use_cookies=True*)
Creates a test client for this application. For informationabout unit testing head over to [*測試 Flask 應用*](#).
Note that if you are testing for assertions or exceptions in yourapplication code, you must set app.testing=True in order for theexceptions to propagate to the test client. Otherwise, the exceptionwill be handled by the application (not visible to the test client) andthe only indication of an AssertionError or other exception will be a500 status code response to the test client. See the [testing](# "flask.Flask.testing")attribute. For example:
~~~
app.testing = True
client = app.test_client()
~~~
The test client can be used in a with block to defer the closing downof the context until the end of the with block. This is useful ifyou want to access the context locals for testing:
~~~
with app.test_client() as c:
rv = c.get('/?vodka=42')
assert request.args['vodka'] == '42'
~~~
See [FlaskClient](# "flask.testing.FlaskClient") for more information.
在 0.4 版更改: added support for with block usage for the client.
0.7 新版功能: The use_cookies parameter was added as well as the abilityto override the client to be used by setting the[test_client_class](# "flask.Flask.test_client_class") attribute.
test_client_class* = None*
the test client that is used with when test_client is used.
0.7 新版功能.
test_request_context(**args*, ***kwargs*)
Creates a WSGI environment from the given values (seewerkzeug.test.EnvironBuilder() for more information, thisfunction accepts the same arguments).
testing
The testing flag. Set this to True to enable the test mode ofFlask extensions (and in the future probably also Flask itself).For example this might activate unittest helpers that have anadditional runtime cost which should not be enabled by default.
If this is enabled and PROPAGATE_EXCEPTIONS is not changed from thedefault it's implicitly enabled.
This attribute can also be configured from the config with theTESTING configuration key. Defaults to False.
trap_http_exception(*e*)
Checks if an HTTP exception should be trapped or not. By defaultthis will return False for all exceptions except for a bad requestkey error if TRAP_BAD_REQUEST_ERRORS is set to True. Italso returns True if TRAP_HTTP_EXCEPTIONS is set to True.
This is called for all HTTP exceptions raised by a view function.If it returns True for any exception the error handler for thisexception is not called and it shows up as regular exception in thetraceback. This is helpful for debugging implicitly raised HTTPexceptions.
0.8 新版功能.
update_template_context(*context*)
Update the template context with some commonly used variables.This injects request, session, config and g into the templatecontext as well as everything template context processors wantto inject. Note that the as of Flask 0.6, the original valuesin the context will not be overridden if a context processordecides to return a value with the same key.
| 參數: | **context** – the context as a dictionary that is updated in placeto add extra variables. |
|-----|-----|
url_build_error_handlers* = None*
A list of functions that are called when [url_for()](# "flask.url_for") raises aBuildError. Each function registered hereis called with error, endpoint and values. If a functionreturns None or raises a BuildError the next function istried.
0.9 新版功能.
url_default_functions* = None*
A dictionary with lists of functions that can be used as URL valuepreprocessors. The key None here is used for application widecallbacks, otherwise the key is the name of the blueprint.Each of these functions has the chance to modify the dictionaryof URL values before they are used as the keyword arguments of theview function. For each function registered this one should alsoprovide a [url_defaults()](# "flask.Flask.url_defaults") function that adds the parametersautomatically again that were removed that way.
0.7 新版功能.
url_defaults(**args*, ***kwargs*)
Callback function for URL defaults for all view functions of theapplication. It's called with the endpoint and values and shouldupdate the values passed in place.
url_map* = None*
The [Map](http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Map "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Map] for this instance. You can usethis to change the routing converters after the class was createdbut before any routes are connected. Example:
~~~
from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
def to_python(self, value):
return value.split(',')
def to_url(self, values):
return ','.join(BaseConverter.to_url(value)
for value in values)
app = Flask(__name__)
app.url_map.converters['list'] = ListConverter
~~~
url_rule_class
The rule object to use for URL rules created. This is used by[add_url_rule()](# "flask.Flask.add_url_rule"). Defaults to [werkzeug.routing.Rule](http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule].
0.7 新版功能.
Rule 的別名
url_value_preprocessor(**args*, ***kwargs*)
Registers a function as URL value preprocessor for all viewfunctions of the application. It's called before the view functionsare called and can modify the url values provided.
url_value_preprocessors* = None*
A dictionary with lists of functions that can be used as URLvalue processor functions. Whenever a URL is built these functionsare called to modify the dictionary of values in place. The keyNone here is used for application widecallbacks, otherwise the key is the name of the blueprint.Each of these functions has the chance to modify the dictionary
0.7 新版功能.
use_x_sendfile
Enable this if you want to use the X-Sendfile feature. Keep inmind that the server has to support this. This only affects filessent with the [send_file()](# "flask.send_file") method.
0.2 新版功能.
This attribute can also be configured from the config with theUSE_X_SENDFILE configuration key. Defaults to False.
view_functions* = None*
A dictionary of all view functions registered. The keys willbe function names which are also used to generate URLs andthe values are the function objects themselves.To register a view function, use the [route()](# "flask.Flask.route") decorator.
wsgi_app(*environ*, *start_response*)
The actual WSGI application. This is not implemented in__call__ so that middlewares can be applied without losing areference to the class. So instead of doing this:
~~~
app = MyMiddleware(app)
~~~
It's a better idea to do this instead:
~~~
app.wsgi_app = MyMiddleware(app.wsgi_app)
~~~
Then you still have the original application object around andcan continue to call methods on it.
在 0.7 版更改: The behavior of the before and after request callbacks was changedunder error conditions and a new callback was added that willalways execute at the end of the request, independent on if anerror occurred or not. See [*回調和錯誤*](#).
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>environ</strong> – a WSGI environment</li><li><strong>start_response</strong> – a callable accepting a status code,a list of headers and an optionalexception context to start the response</li></ul></td></tr></tbody></table>
### 藍圖對象
*class *flask.Blueprint(*name*, *import_name*, *static_folder=None*, *static_url_path=None*, *template_folder=None*, *url_prefix=None*, *subdomain=None*, *url_defaults=None*)
Represents a blueprint. A blueprint is an object that recordsfunctions that will be called with theBlueprintSetupState later to register functionsor other things on the main application. See [*用藍圖實現模塊化的應用*](#) for moreinformation.
0.7 新版功能.
add_app_template_filter(*f*, *name=None*)
Register a custom template filter, available application wide. Like[Flask.add_template_filter()](# "flask.Flask.add_template_filter") but for a blueprint. Works exactlylike the [app_template_filter()](# "flask.Blueprint.app_template_filter") decorator.
| 參數: | **name** – the optional name of the filter, otherwise thefunction name will be used. |
|-----|-----|
add_app_template_global(*f*, *name=None*)
Register a custom template global, available application wide. Like[Flask.add_template_global()](# "flask.Flask.add_template_global") but for a blueprint. Works exactlylike the [app_template_global()](# "flask.Blueprint.app_template_global") decorator.
0.10 新版功能.
| 參數: | **name** – the optional name of the global, otherwise thefunction name will be used. |
|-----|-----|
add_app_template_test(*f*, *name=None*)
Register a custom template test, available application wide. Like[Flask.add_template_test()](# "flask.Flask.add_template_test") but for a blueprint. Works exactlylike the [app_template_test()](# "flask.Blueprint.app_template_test") decorator.
0.10 新版功能.
| 參數: | **name** – the optional name of the test, otherwise thefunction name will be used. |
|-----|-----|
add_url_rule(*rule*, *endpoint=None*, *view_func=None*, ***options*)
Like [Flask.add_url_rule()](# "flask.Flask.add_url_rule") but for a blueprint. The endpoint forthe [url_for()](# "flask.url_for") function is prefixed with the name of the blueprint.
after_app_request(*f*)
Like [Flask.after_request()](# "flask.Flask.after_request") but for a blueprint. Such a functionis executed after each request, even if outside of the blueprint.
after_request(*f*)
Like [Flask.after_request()](# "flask.Flask.after_request") but for a blueprint. This functionis only executed after each request that is handled by a function ofthat blueprint.
app_context_processor(*f*)
Like [Flask.context_processor()](# "flask.Flask.context_processor") but for a blueprint. Such afunction is executed each request, even if outside of the blueprint.
app_errorhandler(*code*)
Like [Flask.errorhandler()](# "flask.Flask.errorhandler") but for a blueprint. Thishandler is used for all requests, even if outside of the blueprint.
app_template_filter(*name=None*)
Register a custom template filter, available application wide. Like[Flask.template_filter()](# "flask.Flask.template_filter") but for a blueprint.
| 參數: | **name** – the optional name of the filter, otherwise thefunction name will be used. |
|-----|-----|
app_template_global(*name=None*)
Register a custom template global, available application wide. Like[Flask.template_global()](# "flask.Flask.template_global") but for a blueprint.
0.10 新版功能.
| 參數: | **name** – the optional name of the global, otherwise thefunction name will be used. |
|-----|-----|
app_template_test(*name=None*)
Register a custom template test, available application wide. Like[Flask.template_test()](# "flask.Flask.template_test") but for a blueprint.
0.10 新版功能.
| 參數: | **name** – the optional name of the test, otherwise thefunction name will be used. |
|-----|-----|
app_url_defaults(*f*)
Same as [url_defaults()](# "flask.Blueprint.url_defaults") but application wide.
app_url_value_preprocessor(*f*)
Same as [url_value_preprocessor()](# "flask.Blueprint.url_value_preprocessor") but application wide.
before_app_first_request(*f*)
Like [Flask.before_first_request()](# "flask.Flask.before_first_request"). Such a function isexecuted before the first request to the application.
before_app_request(*f*)
Like [Flask.before_request()](# "flask.Flask.before_request"). Such a function is executedbefore each request, even if outside of a blueprint.
before_request(*f*)
Like [Flask.before_request()](# "flask.Flask.before_request") but for a blueprint. This functionis only executed before each request that is handled by a function ofthat blueprint.
context_processor(*f*)
Like [Flask.context_processor()](# "flask.Flask.context_processor") but for a blueprint. Thisfunction is only executed for requests handled by a blueprint.
endpoint(*endpoint*)
Like [Flask.endpoint()](# "flask.Flask.endpoint") but for a blueprint. This does notprefix the endpoint with the blueprint name, this has to be doneexplicitly by the user of this method. If the endpoint is prefixedwith a . it will be registered to the current blueprint, otherwiseit's an application independent endpoint.
errorhandler(*code_or_exception*)
Registers an error handler that becomes active for this blueprintonly. Please be aware that routing does not happen local to ablueprint so an error handler for 404 usually is not handled bya blueprint unless it is caused inside a view function. Anotherspecial case is the 500 internal server error which is always lookedup from the application.
Otherwise works as the [errorhandler()](# "flask.Flask.errorhandler") decoratorof the [Flask](# "flask.Flask") object.
get_send_file_max_age(*filename*)
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:
~~~
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)
~~~
0.9 新版功能.
has_static_folder
This is True if the package bound object's container has afolder named 'static'.
0.5 新版功能.
jinja_loader
The Jinja loader for this package bound object.
0.5 新版功能.
make_setup_state(*app*, *options*, *first_registration=False*)
Creates an instance of [BlueprintSetupState()](# "flask.blueprints.BlueprintSetupState")object that is later passed to the register callback functions.Subclasses can override this to return a subclass of the setup state.
open_resource(*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)
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>resource</strong> – the name of the resource. To access resources withinsubfolders use forward slashes as separator.</li><li><strong>mode</strong> – resource file opening mode, default is ‘rb'.</li></ul></td></tr></tbody></table>
record(*func*)
Registers a function that is called when the blueprint isregistered on the application. This function is called with thestate as argument as returned by the [make_setup_state()](# "flask.Blueprint.make_setup_state")method.
record_once(*func*)
Works like [record()](# "flask.Blueprint.record") but wraps the function in anotherfunction that will ensure the function is only called once. If theblueprint is registered a second time on the application, thefunction passed is not called.
register(*app*, *options*, *first_registration=False*)
Called by [Flask.register_blueprint()](# "flask.Flask.register_blueprint") to register a blueprinton the application. This can be overridden to customize the registerbehavior. Keyword arguments from[register_blueprint()](# "flask.Flask.register_blueprint") are directly forwarded to thismethod in the options dictionary.
route(*rule*, ***options*)
Like [Flask.route()](# "flask.Flask.route") but for a blueprint. The endpoint for the[url_for()](# "flask.url_for") function is prefixed with the name of the blueprint.
send_static_file(*filename*)
Function used internally to send static files from the staticfolder to the browser.
0.5 新版功能.
teardown_app_request(*f*)
Like [Flask.teardown_request()](# "flask.Flask.teardown_request") but for a blueprint. Such afunction is executed when tearing down each request, even if outside ofthe blueprint.
teardown_request(*f*)
Like [Flask.teardown_request()](# "flask.Flask.teardown_request") but for a blueprint. Thisfunction is only executed when tearing down requests handled by afunction of that blueprint. Teardown request functions are executedwhen the request context is popped, even when no actual request wasperformed.
url_defaults(*f*)
Callback function for URL defaults for this blueprint. It's calledwith the endpoint and values and should update the values passedin place.
url_value_preprocessor(*f*)
Registers a function as URL value preprocessor for thisblueprint. It's called before the view functions are called andcan modify the url values provided.
### 進入的請求對象
*class *flask.Request(*environ*, *populate_request=True*, *shallow=False*)
The request object used by default in Flask. Remembers thematched endpoint and view arguments.
It is what ends up as [request](# "flask.request"). If you want to replacethe request object used you can subclass this and set[request_class](# "flask.Flask.request_class") to your subclass.
The request object is a [Request](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.Request "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.Request] subclass andprovides all of the attributes Werkzeug defines plus a few Flaskspecific ones.
form
一個包含解析過的從 POST 或 PUT 請求發送的表單對象的[MultiDict](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict] 。請注意上傳的文件不會在這里,而是在[files](# "flask.Request.files") 屬性中。
args
一個包含解析過的查詢字符串( URL 中問號后的部分)內容的[MultiDict](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict] 。
values
一個包含 [form](# "flask.Request.form") 和 [args](# "flask.Request.args") 全部內容的[CombinedMultiDict](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.CombinedMultiDict "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.CombinedMultiDict] 。
cookies
一個包含請求中傳送的所有 cookie 內容的 [dict](http://docs.python.org/dev/library/stdtypes.html#dict "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#dict] 。
stream
如果表單提交的數據沒有以已知的 mimetype 編碼,為性能考慮,數據會不經修改存儲在這個流中。大多數情況下,使用可以把數據提供為字符串的[data](# "flask.Request.data") 是更好的方法。流只返回一次數據。
headers
進入請求的標頭存為一個類似字典的對象。
data
如果進入的請求數據是 Flask 不能處理的 mimetype ,數據將作為字符串存于此。
files
一個包含 POST 和 PUT 請求中上傳的文件的[MultiDict](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict] 。每個文件存儲為[FileStorage](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage] 對象。其基本的行為類似你在 Python 中見到的標準文件對象,差異在于這個對象有一個[save()](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.save "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.save] 方法可以把文件存儲到文件系統上。
environ
底層的 WSGI 環境。
method
當前請求的 HTTP 方法 (POST , GET 等等)
pathscript_rooturlbase_urlurl_root
提供不同的方式來審視當前的 URL 。想象你的應用監聽下面的 URL:
~~~
http://www.example.com/myapplication
~~~
并且用戶請求下面的 URL:
~~~
http://www.example.com/myapplication/page.html?x=y
~~~
這個情況下,上面提到的屬性的值會為如下:
| path | /page.html |
|-----|-----|
| script_root | /myapplication |
| base_url | http://www.example.com/myapplication/page.html |
| url | http://www.example.com/myapplication/page.html?x=y |
| url_root | http://www.example.com/myapplication/ |
is_xhr
當請求由 JavaScript 的 XMLHttpRequest 觸發時,該值為 True 。這只對支持 X-Requested-With 標頭并把該標頭設置為XMLHttpRequest 的庫奏效。這么做的庫有 prototype 、 jQuery 以及Mochikit 等更多。
blueprint
The name of the current blueprint
endpoint
The endpoint that matched the request. This in combination with[view_args](# "flask.Request.view_args") can be used to reconstruct the same or amodified URL. If an exception happened when matching, this willbe None.
get_json(*force=False*, *silent=False*, *cache=True*)
Parses the incoming JSON request data and returns it. Ifparsing fails the [on_json_loading_failed()](# "flask.Request.on_json_loading_failed") method on therequest object will be invoked. By default this function willonly load the json data if the mimetype is application/jsonbut this can be overriden by the force parameter.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>force</strong> – if set to <cite>True</cite> the mimetype is ignored.</li><li><strong>silent</strong> – if set to <cite>False</cite> this method will fail silentlyand return <cite>False</cite>.</li><li><strong>cache</strong> – if set to <cite>True</cite> the parsed JSON data is rememberedon the request.</li></ul></td></tr></tbody></table>
json
If the mimetype is application/json this will contain theparsed JSON data. Otherwise this will be None.
The [get_json()](# "flask.Request.get_json") method should be used instead.
max_content_length
Read-only view of the MAX_CONTENT_LENGTH config key.
module
The name of the current module if the request was dispatchedto an actual module. This is deprecated functionality, use blueprintsinstead.
on_json_loading_failed(*e*)
Called if decoding of the JSON data failed. The return value ofthis method is used by [get_json()](# "flask.Request.get_json") when an error occurred. Thedefault implementation just raises a BadRequest exception.
在 0.10 版更改: Removed buggy previous behavior of generating a random JSONresponse. If you want that behavior back you can triviallyadd it by subclassing.
0.8 新版功能.
routing_exception* = None*
if matching the URL failed, this is the exception that will beraised / was raised as part of the request handling. This isusually a [NotFound](http://werkzeug.pocoo.org/docs/exceptions/#werkzeug.exceptions.NotFound "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/exceptions/#werkzeug.exceptions.NotFound] exception orsomething similar.
url_rule* = None*
the internal URL rule that matched the request. This can beuseful to inspect which methods are allowed for the URL froma before/after handler (request.url_rule.methods) etc.
0.6 新版功能.
view_args* = None*
a dict of view arguments that matched the request. If an exceptionhappened when matching, this will be None.
*class *flask.request
你可以使用全局 request 對象訪問進入的請求數據。 Flask 處理進入的請求數據并允許你用這個全局對象訪問它。如果你工作在多線程環境,Flask 內部保證你總會在當前線程上獲取正確的數據,
這是一個代理。詳情見 [*留意代理*](#) 。
請求對象是一個 [Request](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.Request "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.Request] 子類的實例,提供所有Werkzeug 定義的屬性。這里只對最重要的展示了簡要概述。
### 響應對象
*class *flask.Response(*response=None*, *status=None*, *headers=None*, *mimetype=None*, *content_type=None*, *direct_passthrough=False*)
The response object that is used by default in Flask. Works like theresponse object from Werkzeug but is set to have an HTML mimetype bydefault. Quite often you don't have to create this object yourself because[make_response()](# "flask.Flask.make_response") will take care of that for you.
If you want to replace the response object used you can subclass this andset [response_class](# "flask.Flask.response_class") to your subclass.
headers
Headers 對象表示響應的標頭。
status
字符串表示的響應狀態。
status_code
整數表示的響應狀態。
data
A descriptor that calls get_data() and set_data(). Thisshould not be used and will eventually get deprecated.
mimetype
The mimetype (content type without charset etc.)
set_cookie(*key*, *value=''*, *max_age=None*, *expires=None*, *path='/'*, *domain=None*, *secure=None*, *httponly=False*)
Sets a cookie. The parameters are the same as in the cookie Morselobject in the Python standard library but it accepts unicode data, too.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key (name) of the cookie to be set.</li><li><strong>value</strong> – the value of the cookie.</li><li><strong>max_age</strong> – should be a number of seconds, or <cite>None</cite> (default) ifthe cookie should last only as long as the client'sbrowser session.</li><li><strong>expires</strong> – should be a <cite>datetime</cite> object or UNIX timestamp.</li><li><strong>domain</strong> – if you want to set a cross-domain cookie. For example,<tt class="docutils literal"><span class="pre">domain=".example.com"</span></tt> will set a cookie that isreadable by the domain <tt class="docutils literal"><span class="pre">www.example.com</span></tt>,<tt class="docutils literal"><span class="pre">foo.example.com</span></tt> etc. Otherwise, a cookie will onlybe readable by the domain that set it.</li><li><strong>path</strong> – limits the cookie to a given path, per default it willspan the whole domain.</li></ul></td></tr></tbody></table>
### 會話
如果你設置了 [Flask.secret_key](# "flask.Flask.secret_key") ,你可以在 Flask 應用中使用會話。會話主要使得在請求見保留信息成為可能。 Flask 的實現方法是使用一個簽名的 cookie 。這樣,用戶可以查看會話的內容,但是不能修改它,除非用戶知道密鑰。所以確保密鑰被設置為一個復雜且無法被容易猜測的值。
你可以使用 [session](# "flask.session") 對象來訪問當前的會話:
*class *flask.session
會話對象很像通常的字典,區別是會話對象會追蹤修改。
這是一個代理。更多信息見 [*留意代理*](#) 。
下列屬性是需要關注的:
new
如果會話是新的,該值為 True ,否則為 False 。
modified
當果會話對象檢測到修改,這個值為 True 。注意可變結構的修改不會被自動捕獲,這種情況下你需要自行顯式地設置這個屬性為 True 。這里有 一個例子:
~~~
# this change is not picked up because a mutable object (here
# a list) is changed.
session['objects'].append(42)
# so mark it as modified yourself
session.modified = True
~~~
permanent
如果設為 True ,會話存活[permanent_session_lifetime](# "flask.Flask.permanent_session_lifetime") 秒。默認為 31 天。如果是 False (默認選項),會話會在用戶關閉瀏覽器時刪除。
### 會話接口
0.8 新版功能.
會話接口提供了簡單的途徑來替換 Flask 正在使用的會話實現。
*class *flask.sessions.SessionInterface
The basic interface you have to implement in order to replace thedefault session interface which uses werkzeug's securecookieimplementation. The only methods you have to implement are[open_session()](# "flask.sessions.SessionInterface.open_session") and [save_session()](# "flask.sessions.SessionInterface.save_session"), the others haveuseful defaults which you don't need to change.
The session object returned by the [open_session()](# "flask.sessions.SessionInterface.open_session") method has toprovide a dictionary like interface plus the properties and methodsfrom the [SessionMixin](# "flask.sessions.SessionMixin"). We recommend just subclassing a dictand adding that mixin:
~~~
class Session(dict, SessionMixin):
pass
~~~
If [open_session()](# "flask.sessions.SessionInterface.open_session") returns None Flask will call into[make_null_session()](# "flask.sessions.SessionInterface.make_null_session") to create a session that acts as replacementif the session support cannot work because some requirement is notfulfilled. The default [NullSession](# "flask.sessions.NullSession") class that is createdwill complain that the secret key was not set.
To replace the session interface on an application all you have to dois to assign [flask.Flask.session_interface](# "flask.Flask.session_interface"):
~~~
app = Flask(__name__)
app.session_interface = MySessionInterface()
~~~
0.8 新版功能.
get_cookie_domain(*app*)
Helpful helper method that returns the cookie domain that shouldbe used for the session cookie if session cookies are used.
get_cookie_httponly(*app*)
Returns True if the session cookie should be httponly. Thiscurrently just returns the value of the SESSION_COOKIE_HTTPONLYconfig var.
get_cookie_path(*app*)
Returns the path for which the cookie should be valid. Thedefault implementation uses the value from the SESSION_COOKIE_PATH``config var if it's set, and falls back to APPLICATION_ROOT oruses / if it's None.
get_cookie_secure(*app*)
Returns True if the cookie should be secure. This currentlyjust returns the value of the SESSION_COOKIE_SECURE setting.
get_expiration_time(*app*, *session*)
A helper method that returns an expiration date for the sessionor None if the session is linked to the browser session. Thedefault implementation returns now + the permanent sessionlifetime configured on the application.
is_null_session(*obj*)
Checks if a given object is a null session. Null sessions arenot asked to be saved.
This checks if the object is an instance of [null_session_class](# "flask.sessions.SessionInterface.null_session_class")by default.
make_null_session(*app*)
Creates a null session which acts as a replacement object if thereal session support could not be loaded due to a configurationerror. This mainly aids the user experience because the job of thenull session is to still support lookup without complaining butmodifications are answered with a helpful error message of whatfailed.
This creates an instance of [null_session_class](# "flask.sessions.SessionInterface.null_session_class") by default.
null_session_class
[make_null_session()](# "flask.sessions.SessionInterface.make_null_session") will look here for the class that shouldbe created when a null session is requested. Likewise the[is_null_session()](# "flask.sessions.SessionInterface.is_null_session") method will perform a typecheck againstthis type.
[NullSession](# "flask.sessions.NullSession") 的別名
open_session(*app*, *request*)
This method has to be implemented and must either return Nonein case the loading failed because of a configuration error or aninstance of a session object which implements a dictionary likeinterface + the methods and attributes on [SessionMixin](# "flask.sessions.SessionMixin").
pickle_based* = False*
A flag that indicates if the session interface is pickle based.This can be used by flask extensions to make a decision in regardsto how to deal with the session object.
0.10 新版功能.
save_session(*app*, *session*, *response*)
This is called for actual sessions returned by [open_session()](# "flask.sessions.SessionInterface.open_session")at the end of the request. This is still called during a requestcontext so if you absolutely need access to the request you can dothat.
*class *flask.sessions.SecureCookieSessionInterface
The default session interface that stores sessions in signed cookiesthrough the itsdangerous module.
digest_method()
the hash function to use for the signature. The default is sha1
key_derivation* = 'hmac'*
the name of the itsdangerous supported key derivation. The defaultis hmac.
salt* = 'cookie-session'*
the salt that should be applied on top of the secret key for thesigning of cookie based sessions.
serializer* = <flask.sessions.TaggedJSONSerializer object at 0x3c9c390>*
A python serializer for the payload. The default is a compactJSON derived serializer with support for some extra Python typessuch as datetime objects or tuples.
session_class
SecureCookieSession 的別名
*class *flask.sessions.NullSession(*initial=None*)
Class used to generate nicer error messages if sessions are notavailable. Will still allow read-only access to the empty sessionbut fail on setting.
*class *flask.sessions.SessionMixin
Expands a basic dictionary with an accessors that are expectedby Flask extensions and users for the session.
modified* = True*
for some backends this will always be True, but some backends willdefault this to false and detect changes in the dictionary for aslong as changes do not happen on mutable structures in the session.The default mixin implementation just hardcodes True in.
new* = False*
some session backends can tell you if a session is new, but that isnot necessarily guaranteed. Use with caution. The default mixinimplementation just hardcodes False in.
permanent
this reflects the '_permanent' key in the dict.
flask.sessions.session_json_serializer
Notice
PERMANENT_SESSION_LIFETIME 配置鍵從 Flask 0.8 開始可以是一個整數。你可以自己計算值,或用應用上的[permanent_session_lifetime](# "flask.Flask.permanent_session_lifetime") 屬性來自動轉換結果為一個整數。
### 測試客戶端
*class *flask.testing.FlaskClient(*application*, *response_wrapper=None*, *use_cookies=True*, *allow_subdomain_redirects=False*)
Works like a regular Werkzeug test client but has some knowledge abouthow Flask works to defer the cleanup of the request context stack to theend of a with body when used in a with statement. For general informationabout how to use this class refer to [werkzeug.test.Client](http://werkzeug.pocoo.org/docs/test/#werkzeug.test.Client "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/test/#werkzeug.test.Client].
Basic usage is outlined in the [*測試 Flask 應用*](#) chapter.
session_transaction(**args*, ***kwds*)
When used in combination with a with statement this opens asession transaction. This can be used to modify the session thatthe test client uses. Once the with block is left the session isstored back.
> with client.session_transaction() as session:session[‘value'] = 42
Internally this is implemented by going through a temporary testrequest context and since session handling could depend onrequest variables this function accepts the same arguments as[test_request_context()](# "flask.Flask.test_request_context") which are directlypassed through.
### 應用全局變量
只在一個請求內,從一個函數到另一個函數共享數據,全局變量并不夠好。因為這在線程環境下行不通。 Flask 提供了一個特殊的對象來確保只在活動的請求中有效,并且每個請求都返回不同的值。一言蔽之:它做正確的事情,如同它對[request](# "flask.request") 和 [session](# "flask.session") 做的那樣。
flask.g
在這上存儲你任何你想要存儲的。例如一個數據庫連接或者當前登入的用戶。
從 Flask 0.10 起,對象 g 存儲在應用上下文中而不再是請求上下文中,這意味著即使在應用上下文中它也是可訪問的而不是只能在請求上下文中。在結合 [*偽造資源和上下文*](#) 模式使用來測試時這尤為有用。
另外,在 0.10 中你可以使用 get() 方法來獲取一個屬性或者如果這個屬性沒設置的話將得到 None (或者第二個參數)。這兩種用法現在是沒有區別的:
~~~
user = getattr(flask.g, 'user', None)
user = flask.get.get('user', None)
~~~
現在也能在 g 對象上使用 in 運算符來確定它是否有某個屬性,并且它將使用 yield 關鍵字來生成這樣一個可迭代的包含所有keys的生成器。
這是一個代理。詳情見 [*留意代理*](#) 。
### 有用的函數和類
flask.current_app
指向正在處理請求的應用。這對于想要支持同時運行多個應用的擴展有用。它由應用上下文驅動,而不是請求上下文,所以你可以用[app_context()](# "flask.Flask.app_context") 方法修改這個代理的值。
這是一個代理。詳情見 [*留意代理*](#) 。
flask.has_request_context()
If you have code that wants to test if a request context is there ornot this function can be used. For instance, you may want to take advantageof request information if the request object is available, but failsilently if it is unavailable.
~~~
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and has_request_context():
remote_addr = request.remote_addr
self.remote_addr = remote_addr
~~~
Alternatively you can also just test any of the context bound objects(such as [request](# "flask.request") or [g](# "flask.g") for truthness):
~~~
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and request:
remote_addr = request.remote_addr
self.remote_addr = remote_addr
~~~
0.7 新版功能.
flask.has_app_context()
Works like [has_request_context()](# "flask.has_request_context") but for the applicationcontext. You can also just do a boolean check on the[current_app](# "flask.current_app") object instead.
0.9 新版功能.
flask.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 appendedto the generated URL as query arguments. If the value of a query argumentis None, the whole pair is skipped. In case blueprints are activeyou can shortcut references to the same blueprint by prefixing thelocal endpoint with a dot (.).
This will reference the index function local to the current blueprint:
~~~
url_for('.index')
~~~
For more information, head over to the [*Quickstart*](#).
To integrate applications, [Flask](# "flask.Flask") has a hook to intercept URL builderrors through Flask.build_error_handler. The url_for functionresults in a BuildError when the current app doesnot have a URL for the given endpoint and values. When it does, the[current_app](# "flask.current_app") calls its build_error_handler ifit is not None, which can return a string to use as the result ofurl_for (instead of url_for‘s default to raise theBuildError exception) or re-raise the exception.An example:
~~~
def external_url_handler(error, endpoint, **values):
"Looks up an external URL when `url_for` cannot build a URL."
# This is an example of hooking the build_error_handler.
# Here, lookup_url is some utility function you've built
# which looks up the endpoint in some external URL registry.
url = lookup_url(endpoint, **values)
if url is None:
# External lookup did not have a URL.
# Re-raise the BuildError, in context of original traceback.
exc_type, exc_value, tb = sys.exc_info()
if exc_value is error:
raise exc_type, exc_value, tb
else:
raise error
# url_for will use this result, instead of raising BuildError.
return url
app.build_error_handler = external_url_handler
~~~
Here, error is the instance of BuildError, andendpoint and **values are the arguments passed into url_for. Notethat this is for building URLs outside the current application, and not forhandling 404 NotFound errors.
0.10 新版功能: The _scheme parameter was added.
0.9 新版功能: The _anchor and _method parameters were added.
0.9 新版功能: Calls Flask.handle_build_error() onBuildError.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>endpoint</strong> – the endpoint of the URL (name of the function)</li><li><strong>values</strong> – the variable arguments of the URL rule</li><li><strong>_external</strong> – if set to <cite>True</cite>, an absolute URL is generated. Serveraddress can be changed via <cite>SERVER_NAME</cite> configuration variable whichdefaults to <cite>localhost</cite>.</li><li><strong>_scheme</strong> – a string specifying the desired URL scheme. The <cite>_external</cite>parameter must be set to <cite>True</cite> or a <cite>ValueError</cite> is raised.</li><li><strong>_anchor</strong> – if provided this is added as anchor to the URL.</li><li><strong>_method</strong> – if provided this explicitly specifies an HTTP method.</li></ul></td></tr></tbody></table>
flask.abort(*code*)
拋出一個給定狀態代碼的 [HTTPException](http://werkzeug.pocoo.org/docs/exceptions/#werkzeug.exceptions.HTTPException "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/exceptions/#werkzeug.exceptions.HTTPException] 。例如想要用一個頁面未找到異常來終止請求,你可以調用 abort(404) 。
| 參數: | **code** – the HTTP error code. |
|-----|-----|
flask.redirect(*location*, *code=302*)
Return a response object (a WSGI application) that, if called,redirects the client to the target location. Supported codes are 301,302, 303, 305, and 307. 300 is not supported because it's not a realredirect and 304 because it's the answer for a request with a requestwith defined If-Modified-Since headers.
0.6 新版功能: The location can now be a unicode string that is encoded usingthe iri_to_uri() function.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>location</strong> – the location the response should redirect to.</li><li><strong>code</strong> – the redirect status code. defaults to 302.</li></ul></td></tr></tbody></table>
flask.make_response(**args*)
Sometimes it is necessary to set additional headers in a view. Becauseviews do not have to return response objects but can return a value thatis converted into a response object by Flask itself, it becomes tricky toadd headers to it. This function can be called instead of using a returnand 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 aview function. This for example creates a response with a 404 errorcode:
~~~
response = make_response(render_template('not_found.html'), 404)
~~~
The other use case of this function is to force the return value of aview function into a response which is helpful with viewdecorators:
~~~
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()](# "flask.Flask.make_response")is invoked with it.
- if more than one argument is passed, the arguments are passedto the [flask.Flask.make_response()](# "flask.Flask.make_response") function as tuple.
0.6 新版功能.
flask.send_file(*filename_or_fp*, *mimetype=None*, *as_attachment=False*, *attachment_filename=None*, *add_etags=True*, *cache_timeout=None*, *conditional=False*)
Sends the contents of a file to the client. This will use themost efficient method available and configured. By default it willtry to use the WSGI server's file_wrapper support. Alternativelyyou can set the application's [use_x_sendfile](# "flask.Flask.use_x_sendfile") attributeto True to directly emit an X-Sendfile header. This howeverrequires support of the underlying webserver for X-Sendfile.
By default it will try to guess the mimetype for you, but you canalso explicitly provide one. For extra security you probably wantto send certain files as attachment (HTML for instance). The mimetypeguessing requires a filename or an attachment_filename to beprovided.
Please never pass filenames to this function from user sources withoutchecking them first. Something like this is usually sufficient toavoid security problems:
~~~
if '..' in filename or filename.startswith('/'):
abort(404)
~~~
0.2 新版功能.
0.5 新版功能: The add_etags, cache_timeout and conditional parameters wereadded. The default behavior is now to attach etags.
在 0.7 版更改: mimetype guessing and etag support for file objects wasdeprecated because it was unreliable. Pass a filename if you areable to, otherwise attach an etag yourself. This functionalitywill be removed in Flask 1.0
在 0.9 版更改: cache_timeout pulls its default from application config, when None.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>filename_or_fp</strong> – the filename of the file to send. This isrelative to the <tt class="xref py py-attr docutils literal"><span class="pre">root_path</span></tt> if arelative path is specified.Alternatively a file object might be providedin which case <cite>X-Sendfile</cite> might not work andfall back to the traditional method. Make surethat the file pointer is positioned at the startof data to send before calling <a class="reference internal" href="#flask.send_file" title="flask.send_file"><tt class="xref py py-func docutils literal"><span class="pre">send_file()</span></tt></a>.</li><li><strong>mimetype</strong> – the mimetype of the file if provided, otherwiseauto detection happens.</li><li><strong>as_attachment</strong> – set to <cite>True</cite> if you want to send this file witha <tt class="docutils literal"><span class="pre">Content-Disposition:</span> <span class="pre">attachment</span></tt> header.</li><li><strong>attachment_filename</strong> – the filename for the attachment if itdiffers from the file's filename.</li><li><strong>add_etags</strong> – set to <cite>False</cite> to disable attaching of etags.</li><li><strong>conditional</strong> – set to <cite>True</cite> to enable conditional responses.</li><li><strong>cache_timeout</strong> – the timeout in seconds for the headers. When <cite>None</cite>(default), this value is set by<a class="reference internal" href="#flask.Flask.get_send_file_max_age" title="flask.Flask.get_send_file_max_age"><tt class="xref py py-meth docutils literal"><span class="pre">get_send_file_max_age()</span></tt></a> of<a class="reference internal" href="#flask.current_app" title="flask.current_app"><tt class="xref py py-data docutils literal"><span class="pre">current_app</span></tt></a>.</li></ul></td></tr></tbody></table>
flask.send_from_directory(*directory*, *filename*, ***options*)
Send a file from a given directory with [send_file()](# "flask.send_file"). Thisis a secure way to quickly expose static files from an upload folderor something similar.
Example usage:
~~~
@app.route('/uploads/<path:filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename, as_attachment=True)
~~~
Sending files and Performance
It is strongly recommended to activate either X-Sendfile support inyour webserver or (if no authentication happens) to tell the webserverto serve files for the given path on its own without calling into theweb application for improved performance.
0.5 新版功能.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>directory</strong> – the directory where all the files are stored.</li><li><strong>filename</strong> – the filename relative to that directory todownload.</li><li><strong>options</strong> – optional keyword arguments that are directlyforwarded to <a class="reference internal" href="#flask.send_file" title="flask.send_file"><tt class="xref py py-func docutils literal"><span class="pre">send_file()</span></tt></a>.</li></ul></td></tr></tbody></table>
flask.safe_join(*directory*, *filename*)
Safely join directory and filename.
Example usage:
~~~
@app.route('/wiki/<path:filename>')
def wiki_page(filename):
filename = safe_join(app.config['WIKI_FOLDER'], filename)
with open(filename, 'rb') as fd:
content = fd.read() # Read and process the file content...
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first simple"><li><strong>directory</strong> – the base directory.</li><li><strong>filename</strong> – the untrusted filename relative to that directory.</li></ul></td></tr><tr class="field-even field"><th class="field-name">Raises:</th><td class="field-body"><p class="first last"><tt class="xref py py-class docutils literal"><span class="pre">NotFound</span></tt> if the resulting pathwould fall out of <cite>directory</cite>.</p></td></tr></tbody></table>
flask.escape(*s*) → markup
Convert the characters &, <, >, ‘, and ” in string s to HTML-safesequences. Use this if you need to display text that might containsuch characters in HTML. Marks return value as markup string.
*class *flask.Markup
Marks a string as being safe for inclusion in HTML/XML output withoutneeding to be escaped. This implements the __html__ interface a coupleof frameworks and web applications use. [Markup](# "flask.Markup") is a directsubclass of unicode and provides all the methods of unicode just thatit escapes arguments passed and always returns Markup.
The escape function returns markup objects so that double escaping can'thappen.
The constructor of the [Markup](# "flask.Markup") class can be used for threedifferent things: When passed an unicode object it's assumed to be safe,when passed an object with an HTML representation (has an __html__method) that representation is used, otherwise the object passed isconverted into a unicode string and then assumed to be safe:
~~~
>>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
... def __html__(self):
... return '<a href="#">foo</a>'
...
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')
~~~
If you want object passed being always treated as unsafe you can use the[escape()](# "flask.escape") classmethod to create a [Markup](# "flask.Markup") object:
~~~
>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
~~~
Operations on a markup string are markup aware which means that allarguments are passed through the [escape()](# "flask.escape") function:
~~~
>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo & bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong><blink>hacker here</blink></strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> <foo>')
~~~
*classmethod *escape(*s*)
Escape the string. Works like [escape()](# "flask.escape") with the differencethat for subclasses of [Markup](# "flask.Markup") this function would return thecorrect subclass.
striptags()
Unescape markup into an text_type string and strip all tags. Thisalso resolves known HTML4 and XHTML entities. Whitespace isnormalized to one:
~~~
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
~~~
unescape()
Unescape markup again into an text_type string. This also resolvesknown HTML4 and XHTML entities:
~~~
>>> Markup("Main » <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
~~~
### 消息閃現
flask.flash(*message*, *category='message'*)
Flashes a message to the next request. In order to remove theflashed message from the session and to display it to the user,the template has to call [get_flashed_messages()](# "flask.get_flashed_messages").
在 0.3 版更改: category parameter added.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>message</strong> – the message to be flashed.</li><li><strong>category</strong> – the category for the message. The following valuesare recommended: <tt class="docutils literal"><span class="pre">'message'</span></tt> for any kind of message,<tt class="docutils literal"><span class="pre">'error'</span></tt> for errors, <tt class="docutils literal"><span class="pre">'info'</span></tt> for informationmessages and <tt class="docutils literal"><span class="pre">'warning'</span></tt> for warnings. However anykind of string can be used as category.</li></ul></td></tr></tbody></table>
flask.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 returnthe same messages. By default just the messages are returned,but when with_categories is set to True, the return value willbe a list of tuples in the form (category,message) instead.
Filter the flashed messages to one or more categories by providing thosecategories in category_filter. This allows rendering categories inseparate html blocks. The with_categories and category_filterarguments are distinct:
- with_categories controls whether categories are returned with messagetext (True gives a tuple, where False gives just the message text).
- category_filter filters the messages down to only those matching theprovided categories.
See [*消息閃現*](#) for examples.
在 0.3 版更改: with_categories parameter added.
在 0.9 版更改: category_filter parameter added.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>with_categories</strong> – set to <cite>True</cite> to also receive categories.</li><li><strong>category_filter</strong> – whitelist of categories to limit return values</li></ul></td></tr></tbody></table>
### JSON 支持
Flask 使用 simplejson 來實現JSON。自從 simplejson 既在標準庫中提供也在Flask 的拓展中提供。Flask將首先嘗試自帶的simplejson,如果失敗了就使用標準庫中的json模塊。除此之外,為了更容易定制它還會委托訪問當前應用的JSON的編碼器和解碼器。
所以首先不要這樣用:
> try:import simplejson as jsonexcept ImportError:import json
你可以這樣
~~~
from flask import json
~~~
For usage examples, read the [json](http://docs.python.org/dev/library/json.html#module-json "(在 Python v3.5)") [http://docs.python.org/dev/library/json.html#module-json] documentation.關于更多的用法,請閱讀標準庫中的 [json](http://docs.python.org/dev/library/json.html#module-json "(在 Python v3.5)") [http://docs.python.org/dev/library/json.html#module-json] 文檔。下面的拓展已經默認被集成到了標準庫中JSON模塊里:
1. datetime 對象被序列化為 [**RFC 822**](http://tools.ietf.org/html/rfc822.html) [http://tools.ietf.org/html/rfc822.html] 字符串。
1. 任何帶有 __html__ 方法(比如 [Markup](# "flask.Markup"))將在序列化的時候調用這個方法然后返回的字符串將會被序列化為字符串。
這個 htmlsafe_dumps() 方法也能在 Jinja2 的過濾器中使用,名字為|tojson 。請注意在 script 標簽內部的內容將不會被轉義,所以如果你想在script 內部使用的話請確保它是不可用的通過 |safe 來轉義,除非你正在使用 Flask 0.10,如下:
~~~
<script type=text/javascript>
doSomethingWith({{ user.username|tojson|safe }});
</script>
~~~
flask.json.jsonify(**args*, ***kwargs*)
Creates a [Response](# "flask.Response") with the JSON representation ofthe given arguments with an application/json mimetype. The argumentsto this function are the same as to the [dict](http://docs.python.org/dev/library/stdtypes.html#dict "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#dict] constructor.
Example usage:
~~~
from flask import jsonify
@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
~~~
This will send a JSON response like this to the browser:
~~~
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
~~~
For security reasons only objects are supported toplevel. For moreinformation about this, have a look at [*JSON 安全*](#).
This function's response will be pretty printed if it was not requestedwith X-Requested-With:XMLHttpRequest to simplify debugging unlessthe JSONIFY_PRETTYPRINT_REGULAR config parameter is set to false.
0.2 新版功能.
flask.json.dumps(*obj*, ***kwargs*)
Serialize obj to a JSON formatted str by using the application'sconfigured encoder ([json_encoder](# "flask.Flask.json_encoder")) if there is anapplication on the stack.
This function can return unicode strings or ascii-only bytestrings bydefault which coerce into unicode strings automatically. That behavior bydefault is controlled by the JSON_AS_ASCII configuration variableand can be overriden by the simplejson ensure_ascii parameter.
flask.json.dump(*obj*, *fp*, ***kwargs*)
Like [dumps()](# "flask.json.dumps") but writes into a file object.
flask.json.loads(*s*, ***kwargs*)
Unserialize a JSON object from a string s by using the application'sconfigured decoder ([json_decoder](# "flask.Flask.json_decoder")) if there is anapplication on the stack.
flask.json.load(*fp*, ***kwargs*)
Like [loads()](# "flask.json.loads") but reads from a file object.
*class *flask.json.JSONEncoder(*skipkeys=False*, *ensure_ascii=True*, *check_circular=True*, *allow_nan=True*, *sort_keys=False*, *indent=None*, *separators=None*, *encoding='utf-8'*, *default=None*, *use_decimal=True*, *namedtuple_as_object=True*, *tuple_as_array=True*)
The default Flask JSON encoder. This one extends the default simplejsonencoder by also supporting datetime objects, UUID as well asMarkup objects which are serialized as RFC 822 datetime strings (sameas the HTTP date format). In order to support more data types override the[default()](# "flask.json.JSONEncoder.default") method.
default(*o*)
Implement this method in a subclass such that it returns aserializable object for o, or calls the base implementation (toraise a TypeError).
For example, to support arbitrary iterators, you could implementdefault like this:
~~~
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
~~~
*class *flask.json.JSONDecoder(*encoding=None*, *object_hook=None*, *parse_float=None*, *parse_int=None*, *parse_constant=None*, *strict=True*, *object_pairs_hook=None*)
The default JSON decoder. This one does not change the behavior fromthe default simplejson encoder. Consult the [json](http://docs.python.org/dev/library/json.html#module-json "(在 Python v3.5)") [http://docs.python.org/dev/library/json.html#module-json] documentationfor more information. This decoder is not only used for the loadfunctions of this module but also [Request](# "flask.Request").
### 模板渲染
flask.render_template(*template_name_or_list*, ***context*)
Renders a template from the template folder with the givencontext.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>template_name_or_list</strong> – the name of the template to berendered, or an iterable with template namesthe first one existing will be rendered</li><li><strong>context</strong> – the variables that should be available in thecontext of the template.</li></ul></td></tr></tbody></table>
flask.render_template_string(*source*, ***context*)
Renders a template from the given template source stringwith the given context.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>source</strong> – the sourcecode of the template to berendered</li><li><strong>context</strong> – the variables that should be available in thecontext of the template.</li></ul></td></tr></tbody></table>
flask.get_template_attribute(*template_name*, *attribute*)
Loads a macro (or variable) a template exports. This can be used toinvoke a macro from within Python code. If you for example have atemplate named _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')
~~~
0.2 新版功能.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>template_name</strong> – the name of the template</li><li><strong>attribute</strong> – the name of the variable of macro to access</li></ul></td></tr></tbody></table>
### 配置
*class *flask.Config(*root_path*, *defaults=None*)
Works exactly like a dict but provides ways to fill it from filesor special dictionaries. There are two common patterns to populate theconfig.
Either you can fill the config from a config file:
~~~
app.config.from_pyfile('yourconfig.cfg')
~~~
Or alternatively you can define the configuration options in themodule that calls [from_object()](# "flask.Config.from_object") or provide an import path toa module that should be loaded. It is also possible to tell it touse the same module and with that provide the configuration valuesjust before the call:
~~~
DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)
~~~
In both cases (loading from any Python file or loading from modules),only uppercase keys are added to the config. This makes it possible to uselowercase values in the config file for temporary values that are not addedto the config or to define the config keys in the same file that implementsthe application.
Probably the most interesting way to load configurations is from anenvironment variable pointing to a file:
~~~
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
~~~
In this case before launching the application you have to set thisenvironment variable to the file you want to use. On Linux and OS Xuse the export statement:
~~~
export YOURAPPLICATION_SETTINGS='/path/to/config/file'
~~~
On windows use set instead.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>root_path</strong> – path to which files are read relative from. When theconfig object is created by the application, this isthe application's <tt class="xref py py-attr docutils literal"><span class="pre">root_path</span></tt>.</li><li><strong>defaults</strong> – an optional dictionary of default values</li></ul></td></tr></tbody></table>
from_envvar(*variable_name*, *silent=False*)
Loads a configuration from an environment variable pointing toa configuration file. This is basically just a shortcut with nicererror messages for this line of code:
~~~
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first simple"><li><strong>variable_name</strong> – name of the environment variable</li><li><strong>silent</strong> – set to <cite>True</cite> if you want silent failure for missingfiles.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">bool. <cite>True</cite> if able to load config, <cite>False</cite> otherwise.</p></td></tr></tbody></table>
from_object(*obj*)
Updates the values from the given object. An object can be of oneof the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config.Example usage:
~~~
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
~~~
You should not use this function to load the actual configuration butrather configuration defaults. The actual config should be loadedwith [from_pyfile()](# "flask.Config.from_pyfile") and ideally from a location not within thepackage because the package might be installed system wide.
| 參數: | **obj** – an import name or object |
|-----|-----|
from_pyfile(*filename*, *silent=False*)
Updates the values in the config from a Python file. This functionbehaves as if the file was imported as module with the[from_object()](# "flask.Config.from_object") function.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">參數:</th><td class="field-body"><ul class="first last simple"><li><strong>filename</strong> – the filename of the config. This can either be anabsolute filename or a filename relative to theroot path.</li><li><strong>silent</strong> – set to <cite>True</cite> if you want silent failure for missingfiles.</li></ul></td></tr></tbody></table>
0.7 新版功能: silent parameter.
### 擴展
flask.ext
這個模塊重定向導入模塊到 Flask 擴展。它在 0.8 中被加入,作為導入 Flask擴展的權威方式,并使得我們在發布擴展時能有更大的靈活性。
如果你想使用名為 “Flask-Foo” 的擴展,你應按照下述從 [ext](# "flask.flask.ext")導入:
~~~
from flask.ext import foo
~~~
0.8 新版功能.
### 流的輔助函數
flask.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 encountermemory leaks with badly written WSGI middlewares. The downside is that ifyou are using streamed responses, the generator cannot access request boundinformation 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()))
~~~
0.9 新版功能.
### 有用的內構件
*class *flask.ctx.RequestContext(*app*, *environ*, *request=None*)
The request context contains all request relevant information. It iscreated at the beginning of the request and pushed to the_request_ctx_stack and removed at the end of it. It will create theURL adapter and request object for the WSGI environment provided.
Do not attempt to use this class directly, instead use[test_request_context()](# "flask.Flask.test_request_context") and[request_context()](# "flask.Flask.request_context") to create this object.
When the request context is popped, it will evaluate all thefunctions registered on the application for teardown execution([teardown_request()](# "flask.Flask.teardown_request")).
The request context is automatically popped at the end of the requestfor you. In debug mode the request context is kept around ifexceptions happen so that interactive debuggers have a chance tointrospect the data. With 0.4 this can also be forced for requeststhat did not fail and outside of DEBUG mode. By setting'flask._preserve_context' to True on the WSGI environment thecontext will not pop itself at the end of the request. This is used bythe [test_client()](# "flask.Flask.test_client") for example to implement thedeferred cleanup functionality.
You might find this helpful for unittests where you need theinformation from the context local around for a little longer. Makesure to properly pop() the stack yourself inthat situation, otherwise your unittests will leak memory.
copy()
Creates a copy of this request context with the same request object.This can be used to move a request context to a different greenlet.Because the actual request object is the same this cannot be used tomove a request context to a different thread unless access to therequest object is locked.
0.10 新版功能.
match_request()
Can be overridden by a subclass to hook into the matchingof the request.
pop(*exc=None*)
Pops the request context and unbinds it by doing that. This willalso trigger the execution of functions registered by the[teardown_request()](# "flask.Flask.teardown_request") decorator.
在 0.9 版更改: Added the exc argument.
push()
Binds the request context to the current context.
flask._request_ctx_stack
Flask 中使用的所有的上下文局部對象,都由內部的[LocalStack](http://werkzeug.pocoo.org/docs/local/#werkzeug.local.LocalStack "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/local/#werkzeug.local.LocalStack] 實現。這是一個帶文檔的實例,并且可以在擴展和應用的代碼中使用,但一般來說是不推薦這樣使用的。
下面的屬性在棧的每層上都存在:
app活動的 Flask 應用url_adapter用于匹配請求的 URL 適配器request當前的請求對象session當前的會話對象g擁有 [flask.g](# "flask.g") 對象上全部屬性的對象flashes閃現消息的內部緩存
用法示例:
~~~
from flask import _request_ctx_stack
def get_session():
ctx = _request_ctx_stack.top
if ctx is not None:
return ctx.session
~~~
*class *flask.ctx.AppContext(*app*)
The application context binds an application object implicitlyto the current thread or greenlet, similar to how theRequestContext binds request information. The applicationcontext is also implicitly created if a request context is createdbut the application is not on top of the individual applicationcontext.
pop(*exc=None*)
Pops the app context.
push()
Binds the app context to the current context.
flask._app_ctx_stack
類似請求上下文,但是只跟應用綁定。主要為擴展提供數據存儲。
0.9 新版功能.
*class *flask.blueprints.BlueprintSetupState(*blueprint*, *app*, *options*, *first_registration*)
Temporary holder object for registering a blueprint with theapplication. An instance of this class is created by the[make_setup_state()](# "flask.Blueprint.make_setup_state") method and later passedto all register callback functions.
add_url_rule(*rule*, *endpoint=None*, *view_func=None*, ***options*)
A helper method to register a rule (and optionally a view function)to the application. The endpoint is automatically prefixed with theblueprint's name.
app* = None*
a reference to the current application
blueprint* = None*
a reference to the blueprint that created this setup state.
first_registration* = None*
as blueprints can be registered multiple times with theapplication and not everything wants to be registeredmultiple times on it, this attribute can be used to figureout if the blueprint was registered in the past already.
options* = None*
a dictionary with all options that were passed to the[register_blueprint()](# "flask.Flask.register_blueprint") method.
subdomain* = None*
The subdomain that the blueprint should be active for, Noneotherwise.
url_defaults* = None*
A dictionary with URL defaults that is added to each and everyURL that was defined with the blueprint.
url_prefix* = None*
The prefix that should be used for all URLs defined on theblueprint.
### 信號
0.6 新版功能.
flask.signals_available
當信號系統可用時為 True ,即在 [blinker](http://pypi.python.org/pypi/blinker) [http://pypi.python.org/pypi/blinker] 已經被安裝的情況下。
flask.template_rendered
當一個模板成功渲染的時候,這個信號會發出。這個信號帶著一個模板實例template 和為一個字典的上下文(叫 context )兩個參數被調用。
flask.request_started
這個信號在處建立請求上下文之外的任何請求處理開始前發送。因為請求上下文這個信號在任何對請求的處理前發送,但是正好是在請求的上下文被建立的時候。因為請求上下文已經被約束了,用戶可以使用 [request](# "flask.request") 之類的標準全局代理訪問請求對象。
flask.request_finished
這個信號恰好在請求發送給客戶端之前發送。它傳遞名為 response 的將被發送的響應。
flask.got_request_exception
這個信號在請求處理中拋出異常時發送。它在標準異常處理生效 *之前* ,甚至是在不會處理異常的調試模式下也是如此。這個異常會被將作為一個 exception傳遞到用戶那。
flask.request_tearing_down
這個信號在請求銷毀時發送。它總會被調用,即使發生異常。在這種清況下,造成teardown的異常將會通過一個叫 exc 的關鍵字參數傳遞出來。
在 0.9 版更改: 添加了 exc 參數
flask.appcontext_tearing_down
這個信號在應用上下文銷毀時發送。它總會被調用,即使發生異常。在這種清況下,造成teardown的異常將會通過一個叫 exc 的關鍵字參數傳遞出來。發送者是application對象。
flask.appcontext_pushed
當應用上下文被壓入棧后會發送這個信號。發送者是application對象
0.10 新版功能.
flask.appcontext_popped
當應用上下文出棧后會發送這個信號。發送者是application對象。這常常與[appcontext_tearing_down](# "flask.appcontext_tearing_down") 這個信號一致。
0.10 新版功能.
flask.message_flashed
This signal is sent when the application is flashing a message.The messages is sent as message keyword argument and the當閃現一個消息時會發送這個信號。消息的內容將以 message 關鍵字參數發送,而消息的種類則是 category 關鍵字參數。
0.10 新版功能.
*class *flask.signals.Namespace
[blinker.base.Namespace](http://discorporate.us/projects/Blinker/docs/1.1/api.html#blinker.base.Namespace "(在 Blinker v1.1)") [http://discorporate.us/projects/Blinker/docs/1.1/api.html#blinker.base.Namespace] 的別名,如果 blinker 可用的話。否則,是一個發送偽信號的偽造的類。這個類對想提供與 Flask 相同的備用系統的Flask擴展有用。
signal(*name*, *doc=None*)
在此命名空間中創建一個新信號,如果 blinker 可用的話。否則返回一個帶有不做任何事的發送方法,任何操作都會(包括連接)報錯為[RuntimeError](http://docs.python.org/dev/library/exceptions.html#RuntimeError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#RuntimeError] 的偽信號。
### 基于類的視圖
0.7 新版功能.
*class *flask.views.View
Alternative way to use view functions. A subclass has to implementdispatch_request() which is called with the view arguments fromthe URL routing system. If methods is provided the methodsdo not have to be passed to the [add_url_rule()](# "flask.Flask.add_url_rule")method explicitly:
~~~
class MyView(View):
methods = ['GET']
def dispatch_request(self, name):
return 'Hello %s!' % name
app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))
~~~
When you want to decorate a pluggable view you will have to either do thatwhen the view function is created (by wrapping the return value ofas_view()) or you can use the decorators attribute:
~~~
class SecretView(View):
methods = ['GET']
decorators = [superuser_required]
def dispatch_request(self):
...
~~~
The decorators stored in the decorators list are applied one after anotherwhen the view function is created. Note that you can *not* use the classbased decorators since those would decorate the view class and not thegenerated view function!
*classmethod *as_view(*name*, **class_args*, ***class_kwargs*)
Converts the class into an actual view function that can be usedwith the routing system. Internally this generates a function on thefly which will instantiate the View on each request and callthe dispatch_request() method on it.
The arguments passed to as_view() are forwarded to theconstructor of the class.
decorators* = []*
The canonical way to decorate class-based views is to decorate thereturn value of as_view(). However since this moves parts of thelogic from the class declaration to the place where it's hookedinto the routing system.
You can place one or more decorators in this list and whenever theview function is created the result is automatically decorated.
0.8 新版功能.
dispatch_request()
Subclasses have to override this method to implement theactual view function code. This method is called with allthe arguments from the URL rule.
methods* = None*
A for which methods this pluggable view can handle.
*class *flask.views.MethodView
Like a regular class-based view but that dispatches requests toparticular methods. For instance if you implement a method calledget() it means you will response to 'GET' requests andthe dispatch_request() implementation will automaticallyforward your request to that. Also options is set for youautomatically:
~~~
class CounterAPI(MethodView):
def get(self):
return session.get('counter', 0)
def post(self):
session['counter'] = session.get('counter', 0) + 1
return 'OK'
app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))
~~~
### URL 路由注冊
在路由系統中定義規則可以的方法可以概括為三種:
1. 使用 [flask.Flask.route()](# "flask.Flask.route") 裝飾器
1. 使用 [flask.Flask.add_url_rule()](# "flask.Flask.add_url_rule") 函數
1. 直接訪問暴露為 [flask.Flask.url_map](# "flask.Flask.url_map") 的底層的 Werkzeug 路由系統
路由中的變量部分可以用尖括號指定( /user/<username>)。默認情況下,URL中的變量部分接受任何不帶斜線的字符串,而 <converter:name> 也可以指定不同的轉換器。
變量部分以關鍵字參數傳遞給視圖函數。
下面的轉換器是可用的:
| string | 接受任何不帶斜線的字符串(默認的轉換器) |
|-----|-----|
| int | 接受整數 |
| float | 同 int ,但是接受浮點數 |
| path | 和默認的相似,但也接受斜線 |
這里是一些例子:
~~~
@app.route('/')
def index():
pass
@app.route('/<username>')
def show_user(username):
pass
@app.route('/post/<int:post_id>')
def show_post(post_id):
pass
~~~
需要注意的一個重要細節是 Flask 處理結尾斜線的方式。你可以應用下面兩個規則來保證 URL 的唯一:
1. 如果規則以斜線結尾,當用戶以不帶斜線的形式請求,用戶被自動重定向到帶有結尾斜線的相同頁面。
1. 如果規則結尾沒有斜線,當用戶以帶斜線的形式請求,會拋出一個 404 notfound 。
這與 web 服務器處理靜態文件的方式一致。這使得安全地使用相對鏈接地址成為可能。
你可以為同一個函數定義多個規則。無論如何,他們也要唯一。也可以給定默認值。這里給出一個接受可選頁面的 URL 定義:
~~~
@app.route('/users/', defaults={'page': 1})
@app.route('/users/page/<int:page>')
def show_users(page):
pass
~~~
這指定了 /users/ 為第一頁的 URL ,/users/page/N 為第 N 頁的 URL 。
以下是 [route()](# "flask.Flask.route") 和 [add_url_rule()](# "flask.Flask.add_url_rule")接受的參數。兩者唯一的區別是,帶有路由參數的視圖函數用裝飾器定義,而不是view_func 參數。
| rule | URL 規則的字符串 |
|-----|-----|
| endpoint | 注冊的 URL 規則的末端。如果沒有顯式地規定,Flask 本身假設末端的名稱是視圖函數的名稱,。 |
| view_func | 當請求呈遞到給定的末端時調用的函數。如果沒有提供,可以在用在 [view_functions](# "flask.Flask.view_functions") 字典中以末端作為鍵名存儲,來在之后設定函數。 |
| defaults | 規則默認值的字典。上面的示例介紹了默認值如何工作。 |
| subdomain | 當使用子域名匹配的時候,為子域名設定規則。如果沒有給定,假定為默認的子域名。 |
| **options | 這些選項會被推送給底層的 [Rule](http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule "(在 Werkzeug v0.10)") [http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule]對象。一個 Werkzeug 的變化是 method 選項的處理。methods是這個規則被限定的方法列表( GET , POST 等等)。默認情況下,規則只監聽 GET (也隱式地監聽 HEAD )。從 Flask0.6 開始,OPTIONS 也被隱式地加入,并且做標準的請求處理。它們需要作為關鍵字參數來給定。 |
### 視圖函數選項
對內部使用,視圖函數可以有一些屬性,附加到視圖函數通常沒有控制權的自定義的行為。下面的可選屬性覆蓋 [add_url_rule()](# "flask.Flask.add_url_rule") 的默認值或一般行為:
- __name__: 函數的名稱默認用于末端。如果顯式地提供末端,這個值會使用。此外,它默認以藍圖的名稱作為前綴,并且不能從函數本身自定義。
- methods: 如果沒有在添加 URL 規則時提供 methods 參數。 Flask 會在視圖函數對象上尋找是否存在 methods 屬性。如果存在,它會從上面拉取方法的信息。
- provide_automatic_options: 如果設置了這個屬性, Flask 會強制禁用或啟用 HTTP OPTIONS 響應的自動實現。這對于對單個視圖自定義 OPTIONS響應而使用裝飾器的情況下是有用的。
- required_methods: 如果這個屬性被設置了, 當注冊一個 URL 規則的時候,Flask 將總是會添加這些 methods 即使 methods 參數在 route() 調用的時候被顯式的覆蓋了。
完整的例子:
~~~
def index():
if request.method == 'OPTIONS':
# custom options handling here
...
return 'Hello World!'
index.provide_automatic_options = False
index.methods = ['GET', 'OPTIONS']
app.add_url_rule('/', index)
~~~
0.8 新版功能: 加入了 provide_automatic_options 功能。
? 版權所有 2013, Armin Ronacher.
- 歡迎使用 Flask
- 前言
- 給有經驗程序員的前言
- 安裝
- 快速入門
- 教程
- 介紹 Flaskr
- 步驟 0: 創建文件夾
- 步驟 1: 數據庫模式
- 步驟 2: 應用設置代碼
- 步驟 3: 創建數據庫
- 步驟 4: 請求數據庫連接
- 步驟 5: 視圖函數
- 步驟 6: 模板
- 步驟 7: 添加樣式
- 福利: 應用測試
- 模板
- 測試 Flask 應用
- 記錄應用錯誤
- 配置處理
- 信號
- 即插視圖
- 應用上下文
- 請求上下文
- 用藍圖實現模塊化的應用
- Flask 擴展
- 與 Shell 共舞
- Flask 代碼模式
- 大型應用
- 應用程序的工廠函數
- 應用調度
- 使用 URL 處理器
- 部署和分發
- 使用 Fabric 部署
- 在 Flask 中使用 SQLite 3
- 在 Flask 中使用 SQLAlchemy
- 上傳文件
- 緩存
- 視圖裝飾器
- 使用 WTForms 進行表單驗證
- 模板繼承
- 消息閃現
- 用 jQuery 實現 Ajax
- 自定義錯誤頁面
- 延遲加載視圖
- 在 Flask 中使用 MongoKit
- 添加 Favicon
- 數據流
- 延遲請求回調
- 添加 HTTP Method Overrides
- 請求內容校驗碼
- 基于 Celery 的后臺任務
- 部署選擇
- mod_wsgi (Apache)
- 獨立 WSGI 容器
- uWSGI
- FastCGI
- CGI
- 聚沙成塔
- API
- JSON 支持
- Flask 中的設計決策
- HTML/XHTML 常見問題
- 安全注意事項
- Flask 中的 Unicode
- Flask 擴展開發
- Pocoo 風格指引
- Python 3 支持
- 升級到最新版本
- Flask Changelog
- 許可證
- 術語表