41
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 functions are executed when
the request context is popped, even if not an actual request was performed.
Example:
ctx = app.test_request_context()
ctx.push()
...
ctx.pop()
When ctx.pop() is executed in the above example, the teardown functions
are called just before the requestcontext moves from the stack of active con-
texts. This becomes relevant if you are using such constructs in tests.
Generally teardown functions must take every necessary step to avoid that
they will fail. If they do execute code that might fail they will have to sur-
round the execution of these code by try/except statements and log occur-
ring errors.
When a teardown function was called because of a exception it will be
passed an error object.
Debug Note
In debug mode Flask will not tear down a request on an exception
immediately. Instead if will keep it alive so that the interactive de-
bugger can still access it. This behavior can be controlled by the
PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.
teardown_request_funcs = None
Adictionary with lists of functions that are called after each request, even
if an exception has occurred. The key of the dictionary is the name of
the blueprint this function is active for, None for all requests. These func-
tions are not allowed to modify the request, and their return values are ig-
nored. If an exception occurred while processing the request, it gets passed
to each teardown_request function. To register a function here, use the
teardown_request() decorator.
New in version 0.7.
template_context_processors = None
Adictionary with list of functions that are called without argument to pop-
ulate the template context. The key of the dictionary is the name of the
blueprint this function is active for, None for all requests. Each returns a
dictionary that the template context is updated with. To register a function
here, use the context_processor() decorator.
template_filter(*args, **kwargs)
Adecorator that is used to register custom template filter. You can specify a
193
40
name for the filter, otherwise the function name will be used. Example:
@app.template_filter()
def reverse(s):
return s[::-1]
Parameters name – the optional name of the filter, otherwise the
function name will be used.
template_global(*args, **kwargs)
Adecorator that is used to register a custom template global function. You
can specify a name for the global function, otherwise the function name will
be used. Example:
@app.template_global()
def double(n):
return 2 * n
New in version 0.10.
Parameters name – the optional name of the global function, other-
wise the function name will be used.
template_test(*args, **kwargs)
Adecorator that is used to register custom template test. You can specify a
name for the test, otherwise the function name 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
New in version 0.10.
Parameters name – the optional name of the test, otherwise the
function name will be used.
test_client(use_cookies=True)
Creates a test client for this application. For information about unit testing
head over to Testing Flask Applications.
Note that if you are testing for assertions or exceptions in your application
code, you must set app.testing = True in order for the exceptions to prop-
agate to the test client. Otherwise, the exception will be handled by the
application (not visible to the test client) and the only indication of an As-
sertionError or other exception will be a 500 status code response to the test
client. See the testing attribute. For example:
194
How to C#: Basic SDK Concept of XDoc.PDF for .NET And PDF file text processing like text writing, extracting, searching, etc., are to load a PDF document from file or query data and save the PDF document.
vb extract data from pdf; make pdf form editable in reader
45
app.testing = True
client = app.test_client()
The test client can be used in a with block to defer the closing down of the
context until the end of the with block. This is useful if you want to access
the context locals for testing:
with app.test_client() as s c:
rv = c.get(/?vodka=42)
assert request.args[vodka] == 42
See FlaskClient for more information.
Changed in version 0.4: added support for with block usage for the client.
New in version 0.7: The use_cookies parameter was added as well as the
ability to override the client to be used by setting the test_client_class
attribute.
test_client_class = None
the test client that is used with when test_client is used.
New in version 0.7.
test_request_context(*args, **kwargs)
Creates
a
WSGI environment from
the
given
values (see
werkzeug.test.EnvironBuilder() for more information, this function
accepts the same arguments).
testing
The testing flag. Set this to True to enable the test mode of Flask extensions
(and in the futureprobably also Flask itself). Forexample this mightactivate
unittest helpers that have an additional runtime cost which should not be
enabled by default.
If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
default it’s implicitly enabled.
This attribute can also be configured fromthe config withthe TESTING con-
figuration key. Defaults to False.
trap_http_exception(e)
Checks if an HTTP exception should be trapped or not. By default
this will return False for all exceptions except for a bad request key er-
ror if TRAP_BAD_REQUEST_ERRORS is set to True. It also 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 this exception is not called and
it shows up as regular exception in the traceback. This is helpful for debug-
ging implicitly raised HTTP exceptions.
New in version 0.8.
195
VB.NET PDF: Basic SDK Concept of XDoc.PDF And PDF file text processing like text writing, extracting, searching, etc., are to load a PDF document from file or query data and save the PDF document.
extract data from pdf form to excel; can reader edit pdf forms
42
update_template_context(context)
Update the template context with some commonly used variables. This in-
jects request, session, config andg intothe template contextas well as every-
thing template context processors want to inject. Note that the as of Flask
0.6, the original values in the context will not be overridden if a context
processor decides to return a value with the same key.
Parameters context – the context as a dictionary that is updated in
place to add extra variables.
url_build_error_handlers = None
Alist of functions that are called when url_for() raises a BuildError. Each
function registered here is called with error, endpoint and values. Ifa function
returns None or raises a BuildError the next function is tried.
New in version 0.9.
url_default_functions = None
Adictionary with lists of functions that can be used as URL value prepro-
cessors. The key Nonehere is used for application wide callbacks, otherwise
the key is the name of the blueprint. Each of these functions has the chance
to modify the dictionary of URL values before they are used as the key-
word arguments of the view function. For each function registered this one
should also provide a url_defaults() function that adds the parameters
automatically again that were removed that way.
New in version 0.7.
url_defaults(*args, **kwargs)
Callback function for URL defaults for all view functions of the applica-
tion. It’s called with the endpoint and values and should update the values
passed in place.
url_map = None
TheMap for this instance. You can use this to change the routing converters
after the class was created but 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 n values)
app = Flask(__name__)
app.url_map.converters[list] = ListConverter
url_rule_class
The ruleobject to use forURL rules created. This is used by add_url_rule().
Defaults towerkzeug.routing.Rule.
196
41
New in version 0.7.
alias of Rule
url_value_preprocessor(*args, **kwargs)
Registers a function as URL value preprocessor for all view functions of the
application. It’s called before the view functions are called and can modify
the url values provided.
url_value_preprocessors = None
Adictionary withlists of functions thatcanbe used as URL value processor
functions. Whenever a URL is built these functions are called to modify
the dictionary of values in place. The key None here is used for application
wide callbacks, otherwise the key is the name ofthe blueprint. Each ofthese
functions has the chance to modify the dictionary
New in version 0.7.
use_x_sendfile
Enable this if you want to use the X-Sendfile feature. Keep in mind that the
server has to support this. This only affects files sent with the send_file()
method.
New in version 0.2.
This attribute can also be configured from
the config with the
USE_X_SENDFILE configuration key. Defaults to False.
view_functions = None
Adictionary of all view functions registered. The keys will be function
names whichare also used to generate URLs and the values are the function
objects themselves. To register a view function, use the 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 a reference to the class. So in-
stead 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 and can continue
to call methods on it.
Changed in version 0.7: The behavior of the before and after request call-
backs was changed under error conditions and a new callback was added
thatwill always execute at the end of the request, independenton if an error
occurred or not. See Callbacks and Errors.
Parameters
• environ – a WSGI environment
197
44
• start_response – a callable accepting a status code, a list
of headers and an optional exception context to start the re-
sponse
21.2 Blueprint Objects
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 records functions that will
be called with the BlueprintSetupState later to registerfunctions or other things
on the main application. See Modular Applications with Blueprints for more infor-
mation.
New in version 0.7.
add_app_template_filter(f, name=None)
Register a custom template filter, available application wide.
Like
Flask.add_template_filter() but for a blueprint. Works exactly like the
app_template_filter() decorator.
Parameters name – the optional name of the filter, otherwise the
function name will be used.
add_app_template_global(f, name=None)
Register a custom template global, available application wide. Like
Flask.add_template_global() but for a blueprint. Works exactly like the
app_template_global() decorator.
New in version 0.10.
Parameters name – the optional name of the global, otherwise the
function name will be used.
add_app_template_test(f, name=None)
Register a custom template test, available application wide.
Like
Flask.add_template_test() but for a blueprint. Works exactly like the
app_template_test() decorator.
New in version 0.10.
Parameters name – the optional name of the test, otherwise the
function name will be used.
add_url_rule(rule, endpoint=None, view_func=None, **options)
Like Flask.add_url_rule() but for a blueprint. The endpoint for the
url_for() function is prefixed with the name of the blueprint.
after_app_request(f)
LikeFlask.after_request() but fora blueprint. Sucha functionis executed
after each request, even if outside of the blueprint.
198
42
after_request(f)
Like Flask.after_request() but for a blueprint. This function is only exe-
cuted after each request that is handled by a function of that blueprint.
app_context_processor(f)
Like Flask.context_processor() but for a blueprint. Such a function is ex-
ecuted each request, even if outside of the blueprint.
app_errorhandler(code)
Like Flask.errorhandler() but for a blueprint. This handler 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() but for a blueprint.
Parameters name – the optional name of the filter, otherwise the
function name will be used.
app_template_global(name=None)
Register a custom template global, available application wide. Like
Flask.template_global() but for a blueprint.
New in version 0.10.
Parameters name – the optional name of the global, otherwise the
function name will be used.
app_template_test(name=None)
Register a custom template test, available application wide.
Like
Flask.template_test() but for a blueprint.
New in version 0.10.
Parameters name – the optional name of the test, otherwise the
function name will be used.
app_url_defaults(f)
Same as url_defaults() but application wide.
app_url_value_preprocessor(f)
Same as url_value_preprocessor() but application wide.
before_app_first_request(f)
Like Flask.before_first_request(). Sucha function is executed before the
first request to the application.
before_app_request(f)
Like Flask.before_request(). Such a function is executed before each re-
quest, even if outside of a blueprint.
before_request(f)
Like Flask.before_request() but for a blueprint. This function is only exe-
cuted before each request that is handled by a function of that blueprint.
199
41
context_processor(f)
Like Flask.context_processor() but for a blueprint. This function is only
executed for requests handled by a blueprint.
endpoint(endpoint)
Like Flask.endpoint() but for a blueprint. This does not prefix the end-
point with the blueprint name, this has to be done explicitly by the user of
this method. If the endpoint is prefixed with a . it will be registered to the
current blueprint, otherwise it’s an application independent endpoint.
errorhandler(code_or_exception)
Registers an error handler that becomes activefor this blueprintonly. Please
be aware that routing does not happen local to a blueprint so an error han-
dler for 404 usually is not handled by a blueprint unless it is caused inside
aview function. Another special case is the 500 internal server error which
is always looked up from the application.
Otherwise works as the errorhandler() decorator of the Flask object.
get_send_file_max_age(filename)
Provides default cache_timeout for the send_file() functions.
By default, this function returns SEND_FILE_MAX_AGE_DEFAULT from the con-
figuration of current_app.
Static file functions such as send_from_directory() use this function,
and send_file() calls this function on current_app when the given
cache_timeout is None. If a cache_timeout is given in send_file(), that
timeout is used; otherwise, this method is called.
This allows subclasses to change the behavior when sending files based on
the filename. For example, to set the cache timeout for .js files to 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)
New in version 0.9.
has_static_folder
This is True if the package bound object’s container has a folder named
’static’.
New in version 0.5.
jinja_loader
The Jinja loader for this package bound object.
New in version 0.5.
make_setup_state(app, options, first_registration=False)
Creates an instance of BlueprintSetupState() object that is later passed to
200
Documents you may be interested
Documents you may be interested