class documentation

class Scaffold:

Known subclasses: flask.app.Flask, flask.blueprints.Blueprint

View In Hierarchy

Common behavior shared between ~flask.Flask and ~flask.blueprints.Blueprint.

New in version 2.0.
Parameters
import​_nameThe import name of the module where this object is defined. Usually __name__ should be used.
static​_folderPath to a folder of static files to serve. If this is set, a static route will be added.
static​_url​_pathURL prefix for the static route.
template​_folderPath to a folder containing template files. for rendering. If this is set, a Jinja loader will be added.
root​_pathThe path that static, template, and resource files are relative to. Typically not set, it is discovered based on the import_name.
Static Method ​_get​_exc​_class​_and​_code Get the exception class being handled. For HTTP status codes or HTTPException subclasses, return both the exception and status code.
Method __init__ Undocumented
Method __repr__ Undocumented
Method ​_is​_setup​_finished Undocumented
Method ​_method​_route Undocumented
Method add​_url​_rule Register a rule for routing incoming requests and building URLs. The route decorator is a shortcut to call this with the view_func argument. These are equivalent:
Method after​_request Register a function to run after each request to this object.
Method before​_request Register a function to run before each request.
Method context​_processor Registers a template context processor function.
Method delete Shortcut for route with methods=["DELETE"].
Method endpoint Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule.
Method errorhandler Register a function to handle errors by code or exception class.
Method get Shortcut for route with methods=["GET"].
Method get​_send​_file​_max​_age Used by send_file to determine the max_age cache value for a given file path if it wasn't passed.
Method open​_resource Open a resource file relative to root_path for reading.
Method patch Shortcut for route with methods=["PATCH"].
Method post Shortcut for route with methods=["POST"].
Method put Shortcut for route with methods=["PUT"].
Method register​_error​_handler Alternative error attach function to the errorhandler decorator that is more straightforward to use for non decorator usage.
Method route Decorate a view function to register it with the given URL rule and options. Calls add_url_rule, which has more details about the implementation.
Method send​_static​_file No summary
Method static​_folder.setter Undocumented
Method static​_url​_path.setter Undocumented
Method teardown​_request No summary
Method url​_defaults Callback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place.
Method url​_value​_preprocessor Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request functions.
Class Variable json​_decoder Undocumented
Class Variable json​_encoder Undocumented
Class Variable name Undocumented
Instance Variable ​_static​_folder Undocumented
Instance Variable ​_static​_url​_path Undocumented
Instance Variable after​_request​_funcs Undocumented
Instance Variable before​_request​_funcs Undocumented
Instance Variable cli Undocumented
Instance Variable error​_handler​_spec Undocumented
Instance Variable import​_name Undocumented
Instance Variable root​_path Undocumented
Instance Variable teardown​_request​_funcs Undocumented
Instance Variable template​_context​_processors Undocumented
Instance Variable template​_folder Undocumented
Instance Variable url​_default​_functions Undocumented
Instance Variable url​_value​_preprocessors Undocumented
Instance Variable view​_functions Undocumented
Property has​_static​_folder True if static_folder is set.
Property jinja​_loader The Jinja loader for this object's templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set.
Property static​_folder The absolute path to the configured static folder. None if no static folder is set.
Property static​_url​_path The URL prefix that the static route will be accessible from.
@staticmethod
def _get_exc_class_and_code(exc_class_or_code):
Get the exception class being handled. For HTTP status codes or HTTPException subclasses, return both the exception and status code.
Parameters
exc​_class​_or​_code:t.Union[t.Type[Exception], int]Any exception class, or an HTTP status code as an integer.
Returns
t.Tuple[t.Type[Exception], t.Optional[int]]Undocumented
def __init__(self, import_name, static_folder=None, static_url_path=None, template_folder=None, root_path=None):

Undocumented

Parameters
import​_name:strUndocumented
static​_folder:t.Optional[t.Union[str, os.PathLike]]Undocumented
static​_url​_path:t.Optional[str]Undocumented
template​_folder:t.Optional[str]Undocumented
root​_path:t.Optional[str]Undocumented
def __repr__(self):

Undocumented

Returns
strUndocumented
def _is_setup_finished(self):

Undocumented

Returns
boolUndocumented
def _method_route(self, method, rule, options):

Undocumented

Parameters
method:strUndocumented
rule:strUndocumented
options:dictUndocumented
Returns
t.CallableUndocumented
@setupmethod
def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):

Register a rule for routing incoming requests and building URLs. The route decorator is a shortcut to call this with the view_func argument. These are equivalent:

@app.route("/")
def index():
    ...
def index():
    ...

app.add_url_rule("/", view_func=index)

See :ref:`url-route-registrations`.

The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn't passed. An error will be raised if a function has already been registered for the endpoint.

The methods parameter defaults to ["GET"]. HEAD is always added automatically, and OPTIONS is added automatically by default.

view_func does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the endpoint decorator.

app.add_url_rule("/", endpoint="index")

@app.endpoint("index")
def index():
    ...

If view_func has a required_methods attribute, those methods are added to the passed and automatic methods. If it has a provide_automatic_methods attribute, it is used as the default if the parameter is not passed.

Parameters
rule:strThe URL rule string.
endpoint:t.Optional[str]The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to view_func.__name__.
view​_func:t.Optional[t.Callable]The view function to associate with the endpoint name.
provide​_automatic​_options:t.Optional[bool]Add the OPTIONS method and respond to OPTIONS requests automatically.
**options:t.AnyExtra options passed to the ~werkzeug.routing.Rule object.
@setupmethod
def after_request(self, f):

Register a function to run after each request to this object.

The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.

If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request for that.

Parameters
f:AfterRequestCallableUndocumented
Returns
AfterRequestCallableUndocumented
@setupmethod
def before_request(self, f):

Register a function to run before each request.

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

@app.before_request
def load_user():
    if "user_id" in session:
        g.user = db.session.get(session["user_id"])

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

Parameters
f:BeforeRequestCallableUndocumented
Returns
BeforeRequestCallableUndocumented
@setupmethod
def context_processor(self, f):
Registers a template context processor function.
Parameters
f:TemplateContextProcessorCallableUndocumented
Returns
TemplateContextProcessorCallableUndocumented
def delete(self, rule, **options):

Shortcut for route with methods=["DELETE"].

New in version 2.0.
Parameters
rule:strUndocumented
**options:t.AnyUndocumented
Returns
t.CallableUndocumented
def endpoint(self, endpoint):

Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule.

app.add_url_rule("/ex", endpoint="example")

@app.endpoint("example")
def example():
    ...
Parameters
endpoint:strThe endpoint name to associate with the view function.
Returns
t.CallableUndocumented
@setupmethod
def errorhandler(self, code_or_exception):

Register a function to handle errors by code or exception class.

A decorator that is used to register a function given an error 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
New in version 0.7: Use register_error_handler instead of modifying error_handler_spec directly, for application wide error handlers.
New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the ~werkzeug.exceptions.HTTPException class.
Parameters
code​_or​_exception:t.Union[t.Type[GenericException], int]the code as integer for the handler, or an arbitrary exception
Returns
t.Callable[[ErrorHandlerCallable[GenericException]], ErrorHandlerCallable[GenericException]]Undocumented
def get(self, rule, **options):

Shortcut for route with methods=["GET"].

New in version 2.0.
Parameters
rule:strUndocumented
**options:t.AnyUndocumented
Returns
t.CallableUndocumented
def get_send_file_max_age(self, filename):

Used by send_file to determine the max_age cache value for a given file path if it wasn't passed.

By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of ~flask.current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable.

Changed in version 2.0: The default configuration is None instead of 12 hours.
New in version 0.9.
Parameters
filename:t.Optional[str]Undocumented
Returns
t.Optional[int]Undocumented
def open_resource(self, resource, mode='rb'):

Open a resource file relative to root_path for reading.

For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with:

with app.open_resource("schema.sql") as f:
    conn.executescript(f.read())
Parameters
resource:strPath to the resource relative to root_path.
mode:strOpen the file in this mode. Only reading is supported, valid values are "r" (or "rt") and "rb".
Returns
t.IO[t.AnyStr]Undocumented
def patch(self, rule, **options):

Shortcut for route with methods=["PATCH"].

New in version 2.0.
Parameters
rule:strUndocumented
**options:t.AnyUndocumented
Returns
t.CallableUndocumented
def post(self, rule, **options):

Shortcut for route with methods=["POST"].

New in version 2.0.
Parameters
rule:strUndocumented
**options:t.AnyUndocumented
Returns
t.CallableUndocumented
def put(self, rule, **options):

Shortcut for route with methods=["PUT"].

New in version 2.0.
Parameters
rule:strUndocumented
**options:t.AnyUndocumented
Returns
t.CallableUndocumented
@setupmethod
def register_error_handler(self, code_or_exception, f):

Alternative error attach function to the errorhandler decorator that is more straightforward to use for non decorator usage.

New in version 0.7.
Parameters
code​_or​_exception:t.Union[t.Type[GenericException], int]Undocumented
f:ErrorHandlerCallable[GenericException]Undocumented
def route(self, rule, **options):

Decorate a view function to register it with the given URL rule and options. Calls add_url_rule, which has more details about the implementation.

@app.route("/")
def index():
    return "Hello, World!"

See :ref:`url-route-registrations`.

The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn't passed.

The methods parameter defaults to ["GET"]. HEAD and OPTIONS are added automatically.

Parameters
rule:strThe URL rule string.
**options:t.AnyExtra options passed to the ~werkzeug.routing.Rule object.
Returns
t.CallableUndocumented
def send_static_file(self, filename):

The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set.

New in version 0.5.
Parameters
filename:strUndocumented
Returns
ResponseUndocumented
@static_folder.setter
def static_folder(self, value):

Undocumented

Parameters
value:t.Optional[t.Union[str, os.PathLike]]Undocumented
@static_url_path.setter
def static_url_path(self, value):

Undocumented

Parameters
value:t.Optional[str]Undocumented
@setupmethod
def teardown_request(self, f):

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 request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.

Teardown functions must avoid raising exceptions, since they . If they execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors.

When a teardown function was called because of an exception it will be passed an error object.

The return values of teardown functions are ignored.

Debug Note

In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.

Parameters
f:TeardownCallableUndocumented
Returns
TeardownCallableUndocumented
@setupmethod
def url_defaults(self, f):
Callback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place.
Parameters
f:URLDefaultCallableUndocumented
Returns
URLDefaultCallableUndocumented
@setupmethod
def url_value_preprocessor(self, f):

Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request functions.

The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view.

The function is passed the endpoint name and values dict. The return value is ignored.

Parameters
f:URLValuePreprocessorCallableUndocumented
Returns
URLValuePreprocessorCallableUndocumented
json_decoder: t.Optional[t.Type[JSONDecoder]] =

Undocumented

json_encoder: t.Optional[t.Type[JSONEncoder]] =

Undocumented

name: str =

Undocumented

_static_folder =

Undocumented

_static_url_path =

Undocumented

after_request_funcs: t.Dict[AppOrBlueprintKey, t.List[AfterRequestCallable]] =

Undocumented

before_request_funcs: t.Dict[AppOrBlueprintKey, t.List[BeforeRequestCallable]] =

Undocumented

cli =

Undocumented

error_handler_spec: t.Dict[AppOrBlueprintKey, t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable[Exception]]]] =

Undocumented

import_name =

Undocumented

root_path =

Undocumented

teardown_request_funcs: t.Dict[AppOrBlueprintKey, t.List[TeardownCallable]] =

Undocumented

template_context_processors: t.Dict[AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]] =

Undocumented

template_folder =

Undocumented

url_default_functions: t.Dict[AppOrBlueprintKey, t.List[URLDefaultCallable]] =

Undocumented

url_value_preprocessors: t.Dict[AppOrBlueprintKey, t.List[URLValuePreprocessorCallable]] =

Undocumented

view_functions: t.Dict[str, t.Callable] =

Undocumented

@property
has_static_folder: bool =

True if static_folder is set.

New in version 0.5.
@locked_cached_property
jinja_loader: t.Optional[FileSystemLoader] =

The Jinja loader for this object's templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set.

New in version 0.5.
@property
static_folder: t.Optional[str] =
The absolute path to the configured static folder. None if no static folder is set.
@property
static_url_path: t.Optional[str] =

The URL prefix that the static route will be accessible from.

If it was not configured during init, it is derived from static_folder.