doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
Foreword Read this before you get started with Flask. This hopefully answers some questions about the purpose and goals of the project, and when you should or should not be using it. What does “micro” mean? “Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly...
flask.foreword.index
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 return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will...
flask.api.index#flask.get_flashed_messages
flask.get_template_attribute(template_name, attribute) Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named _cider.html with the following contents: {% macro hello(name) %}Hello {{ name }}!{% endmacro %} You can access th...
flask.api.index#flask.get_template_attribute
flask.has_app_context() Works like has_request_context() but for the application context. You can also just do a boolean check on the current_app object instead. Changelog New in version 0.9. Return type bool
flask.api.index#flask.has_app_context
flask.has_request_context() If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. class User(db.Model): def __init__(self, ...
flask.api.index#flask.has_request_context
Installation Python Version We recommend using the latest version of Python. Flask supports Python 3.6 and newer. Dependencies These distributions will be installed automatically when installing Flask. Werkzeug implements WSGI, the standard Python interface between applications and servers. Jinja is a template langu...
flask.installation.index
class flask.json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None) The default JSON decoder. This does not change any behavior from the built-in json.JSONDecoder. Assign a subclass of this to flask.Flask.json_decoder or flask.Blueprint.json_de...
flask.api.index#flask.json.JSONDecoder
class flask.json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) The default JSON encoder. Handles extra types compared to the built-in json.JSONEncoder. datetime.datetime and datetime.date are serialized to RFC 822 ...
flask.api.index#flask.json.JSONEncoder
default(o) Convert o to a JSON serializable type. See json.JSONEncoder.default(). Python does not support overriding how basic types like str or list are serialized, they are handled before this method. Parameters o (Any) – Return type Any
flask.api.index#flask.json.JSONEncoder.default
flask.json.jsonify(*args, **kwargs) Serialize data to JSON and wrap it in a Response with the application/json mimetype. Uses dumps() to serialize the data, but args and kwargs are treated as data rather than arguments to json.dumps(). Single argument: Treated as a single value. Multiple arguments: Treated as a list...
flask.api.index#flask.json.jsonify
JSONIFY_MIMETYPE The mimetype of jsonify responses. Default: 'application/json'
flask.config.index#JSONIFY_MIMETYPE
JSONIFY_PRETTYPRINT_REGULAR jsonify responses will be output with newlines, spaces, and indentation for easier reading by humans. Always enabled in debug mode. Default: False
flask.config.index#JSONIFY_PRETTYPRINT_REGULAR
class flask.json.tag.JSONTag(serializer) Base class for defining type tags for TaggedJSONSerializer. Parameters serializer (TaggedJSONSerializer) – Return type None check(value) Check if the given value should be tagged by this tag. Parameters value (Any) – Return type bool key: Optional[str] = ...
flask.api.index#flask.json.tag.JSONTag
check(value) Check if the given value should be tagged by this tag. Parameters value (Any) – Return type bool
flask.api.index#flask.json.tag.JSONTag.check
key: Optional[str] = None The tag to mark the serialized object with. If None, this tag is only used as an intermediate step during tagging.
flask.api.index#flask.json.tag.JSONTag.key
tag(value) Convert the value to a valid JSON type and add the tag structure around it. Parameters value (Any) – Return type Any
flask.api.index#flask.json.tag.JSONTag.tag
to_json(value) Convert the Python object to an object that is a valid JSON type. The tag will be added later. Parameters value (Any) – Return type Any
flask.api.index#flask.json.tag.JSONTag.to_json
to_python(value) Convert the JSON representation back to the correct type. The tag will already be removed. Parameters value (Any) – Return type Any
flask.api.index#flask.json.tag.JSONTag.to_python
JSON_AS_ASCII Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON returned from jsonify will contain Unicode characters. This has security implications when rendering the JSON into JavaScript in templates, and should typically remain enabled. Default: True
flask.config.index#JSON_AS_ASCII
JSON_SORT_KEYS Sort the keys of JSON objects alphabetically. This is useful for caching because it ensures the data is serialized the same way no matter what Python’s hash seed is. While not recommended, you can disable this for a possible performance improvement at the cost of caching. Default: True
flask.config.index#JSON_SORT_KEYS
flask.json.load(fp, app=None, **kwargs) Deserialize an object from JSON read from a file object. Takes the same arguments as the built-in json.load(), with some defaults from application configuration. Parameters fp (IO[str]) – File object to read JSON from. app (Optional[Flask]) – Use this app’s config instead ...
flask.api.index#flask.json.load
flask.json.loads(s, app=None, **kwargs) Deserialize an object from a string of JSON. Takes the same arguments as the built-in json.loads(), with some defaults from application configuration. Parameters s (str) – JSON string to deserialize. app (Optional[Flask]) – Use this app’s config instead of the active app c...
flask.api.index#flask.json.loads
flask.cli.load_dotenv(path=None) Load “dotenv” files in order of precedence to set environment variables. If an env var is already set it is not overwritten, so earlier files in the list are preferred over later files. This is a no-op if python-dotenv is not installed. Parameters path – Load the file at this locati...
flask.api.index#flask.cli.load_dotenv
Logging Flask uses standard Python logging. Messages about your Flask application are logged with app.logger, which takes the same name as app.name. This logger can also be used to log your own messages. @app.route('/login', methods=['POST']) def login(): user = get_user(request.form['username']) if user.check...
flask.logging.index
flask.make_response(*args) Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return ...
flask.api.index#flask.make_response
class flask.Markup(base='', encoding=None, errors='strict') A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or because it was marked safe. Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape the text...
flask.api.index#flask.Markup
classmethod escape(s) Escape a string. Calls escape() and ensures that for subclasses the correct type is returned. Parameters s (Any) – Return type markupsafe.Markup
flask.api.index#flask.Markup.escape
striptags() unescape() the markup, remove tags, and normalize whitespace to single spaces. >>> Markup("Main &raquo; <em>About</em>").striptags() 'Main » About' Return type str
flask.api.index#flask.Markup.striptags
unescape() Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent. >>> Markup("Main &raquo; <em>About</em>").unescape() 'Main » <em>About</em>' Return type str
flask.api.index#flask.Markup.unescape
MAX_CONTENT_LENGTH Don’t read more than this many bytes from the incoming request data. If not set and the request does not specify a CONTENT_LENGTH, no data will be read for security. Default: None
flask.config.index#MAX_CONTENT_LENGTH
MAX_COOKIE_SIZE Warn if cookie headers are larger than this many bytes. Defaults to 4093. Larger cookies may be silently ignored by browsers. Set to 0 to disable the warning.
flask.config.index#MAX_COOKIE_SIZE
class flask.views.MethodView A class-based view that dispatches request methods to the corresponding class methods. For example, if you implement a get method, it will be used to handle GET requests. class CounterAPI(MethodView): def get(self): return session.get('counter', 0) def post(self): ...
flask.api.index#flask.views.MethodView
dispatch_request(*args, **kwargs) Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule. Parameters args (Any) – kwargs (Any) – Return type Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tupl...
flask.api.index#flask.views.MethodView.dispatch_request
class signals.Namespace An alias for blinker.base.Namespace if blinker is available, otherwise a dummy class that creates fake signals. This class is available for Flask extensions that want to provide the same fallback system as Flask itself. signal(name, doc=None) Creates a new signal for this namespace if blin...
flask.api.index#flask.signals.Namespace
signal(name, doc=None) Creates a new signal for this namespace if blinker is available, otherwise returns a fake signal that has a send method that will do nothing but will fail with a RuntimeError for all other operations, including connecting.
flask.api.index#flask.signals.Namespace.signal
class flask.sessions.NullSession(initial=None) Class used to generate nicer error messages if sessions are not available. Will still allow read-only access to the empty session but fail on setting. Parameters initial (Any) – Return type None
flask.api.index#flask.sessions.NullSession
flask.cli.pass_script_info(f) Marks a function so that an instance of ScriptInfo is passed as first argument to the click callback. Parameters f (click.decorators.F) – Return type click.decorators.F
flask.api.index#flask.cli.pass_script_info
PERMANENT_SESSION_LIFETIME If session.permanent is true, the cookie’s expiration will be set this number of seconds in the future. Can either be a datetime.timedelta or an int. Flask’s default cookie implementation validates that the cryptographic signature is not older than this value. Default: timedelta(days=31) (2...
flask.config.index#PERMANENT_SESSION_LIFETIME
PREFERRED_URL_SCHEME Use this scheme for generating external URLs when not in a request context. Default: 'http'
flask.config.index#PREFERRED_URL_SCHEME
PRESERVE_CONTEXT_ON_EXCEPTION Don’t pop the request context when an exception occurs. If not set, this is true if DEBUG is true. This allows debuggers to introspect the request data on errors, and should normally not need to be set directly. Default: None
flask.config.index#PRESERVE_CONTEXT_ON_EXCEPTION
PROPAGATE_EXCEPTIONS Exceptions are re-raised rather than being handled by the app’s error handlers. If not set, this is implicitly true if TESTING or DEBUG is enabled. Default: None
flask.config.index#PROPAGATE_EXCEPTIONS
Quickstart Eager to get started? This page gives a good introduction to Flask. Follow Installation to set up a project and install Flask first. A Minimal Application A minimal Flask application looks something like this: from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>H...
flask.quickstart.index
flask.redirect(location, code=302, Response=None) Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with ...
flask.api.index#flask.redirect
flask.render_template(template_name_or_list, **context) Renders a template from the template folder with the given context. Parameters template_name_or_list (Union[str, List[str]]) – the name of the template to be rendered, or an iterable with template names the first one existing will be rendered context (Any) ...
flask.api.index#flask.render_template
flask.render_template_string(source, **context) Renders a template from the given template source string with the given context. Template variables will be autoescaped. Parameters source (str) – the source code of the template to be rendered context (Any) – the variables that should be available in the context o...
flask.api.index#flask.render_template_string
class flask.Request(environ, populate_request=True, shallow=False) The request object used by default in Flask. Remembers the matched endpoint and view arguments. It is what ends up as request. If you want to replace the request object used you can subclass this and set request_class to your subclass. The request obj...
flask.api.index#flask.Request
access_control_request_headers Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.
flask.api.index#flask.Request.access_control_request_headers
access_control_request_method Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.
flask.api.index#flask.Request.access_control_request_method
classmethod application(f) Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the request object will be closed automatically: @Request.application def my_wsgi_app(request): ...
flask.api.index#flask.Request.application
close() Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. Changelog New in version 0.9. Return type None
flask.api.index#flask.Request.close
content_encoding The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type ...
flask.api.index#flask.Request.content_encoding
content_md5 The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against m...
flask.api.index#flask.Request.content_md5
content_type The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
flask.api.index#flask.Request.content_type
date The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. Changed in version 2.0: The datetime object is timezone-aware.
flask.api.index#flask.Request.date
dict_storage_class alias of werkzeug.datastructures.ImmutableMultiDict
flask.api.index#flask.Request.dict_storage_class
environ: WSGIEnvironment The WSGI environment containing HTTP headers and information from the WSGI server.
flask.api.index#flask.Request.environ
form_data_parser_class alias of werkzeug.formparser.FormDataParser
flask.api.index#flask.Request.form_data_parser_class
classmethod from_values(*args, **kwargs) Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client ...
flask.api.index#flask.Request.from_values
get_data(cache=True, as_text=False, parse_form_data=False) This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting cache to False. Usually it’s a bad idea to call this method without checking the content length first as a clien...
flask.api.index#flask.Request.get_data
get_json(force=False, silent=False, cache=True) Parse data as JSON. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. If parsing fails, on_json_loading_failed() is called and its return value is used as the return value. Parameters force (bool) – Ignore the mimetype and ...
flask.api.index#flask.Request.get_json
headers The headers received with the request.
flask.api.index#flask.Request.headers
input_stream The WSGI input stream. In general it’s a bad idea to use this one because you can easily read past the boundary. Use the stream instead.
flask.api.index#flask.Request.input_stream
is_multiprocess boolean that is True if the application is served by a WSGI server that spawns multiple processes.
flask.api.index#flask.Request.is_multiprocess
is_multithread boolean that is True if the application is served by a multithreaded WSGI server.
flask.api.index#flask.Request.is_multithread
is_run_once boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time.
flask.api.index#flask.Request.is_run_once
list_storage_class alias of werkzeug.datastructures.ImmutableList
flask.api.index#flask.Request.list_storage_class
make_form_data_parser() Creates the form data parser. Instantiates the form_data_parser_class with some parameters. Changelog New in version 0.8. Return type werkzeug.formparser.FormDataParser
flask.api.index#flask.Request.make_form_data_parser
max_forwards The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.
flask.api.index#flask.Request.max_forwards
method The method the request was made with, such as GET.
flask.api.index#flask.Request.method
on_json_loading_failed(e) Called if get_json() parsing fails and isn’t silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest. Parameters e (Exception) – Return type NoReturn
flask.api.index#flask.Request.on_json_loading_failed
origin The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.
flask.api.index#flask.Request.origin
parameter_storage_class alias of werkzeug.datastructures.ImmutableMultiDict
flask.api.index#flask.Request.parameter_storage_class
path The path part of the URL after root_path. This is the path used for routing within the application.
flask.api.index#flask.Request.path
query_string The part of the URL after the “?”. This is the raw value, use args for the parsed values.
flask.api.index#flask.Request.query_string
referrer The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).
flask.api.index#flask.Request.referrer
remote_addr The address of the client sending the request.
flask.api.index#flask.Request.remote_addr
remote_user If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.
flask.api.index#flask.Request.remote_user
root_path The prefix that the application is mounted under, without a trailing slash. path comes after this.
flask.api.index#flask.Request.root_path
routing_exception: Optional[Exception] = None If matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a NotFound exception or something similar.
flask.api.index#flask.Request.routing_exception
scheme The URL scheme of the protocol the request used, such as https or wss.
flask.api.index#flask.Request.scheme
server The address of the server. (host, port), (path, None) for unix sockets, or None if not known.
flask.api.index#flask.Request.server
shallow: bool Set when creating the request object. If True, reading from the request body will cause a RuntimeException. Useful to prevent modifying the stream from middleware.
flask.api.index#flask.Request.shallow
url_rule: Optional[Rule] = None The internal URL rule that matched the request. This can be useful to inspect which methods are allowed for the URL from a before/after handler (request.url_rule.methods) etc. Though if the request’s method was invalid for the URL rule, the valid list is available in routing_exception....
flask.api.index#flask.Request.url_rule
user_agent_class alias of werkzeug.useragents._UserAgent
flask.api.index#flask.Request.user_agent_class
view_args: Optional[Dict[str, Any]] = None A dict of view arguments that matched the request. If an exception happened when matching, this will be None.
flask.api.index#flask.Request.view_args
class flask.ctx.RequestContext(app, environ, request=None, session=None) The request context contains all request relevant information. It is created at the beginning of the request and pushed to the _request_ctx_stack and removed at the end of it. It will create the URL adapter and request object for the WSGI enviro...
flask.api.index#flask.ctx.RequestContext
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 to move a request context to a different thread unless access to the request object is locked. Changelog Ch...
flask.api.index#flask.ctx.RequestContext.copy
match_request() Can be overridden by a subclass to hook into the matching of the request. Return type None
flask.api.index#flask.ctx.RequestContext.match_request
pop(exc=<object object>) Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the teardown_request() decorator. Changelog Changed in version 0.9: Added the exc argument. Parameters exc (Optional[BaseException]) – Return type None
flask.api.index#flask.ctx.RequestContext.pop
push() Binds the request context to the current context. Return type None
flask.api.index#flask.ctx.RequestContext.push
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 the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you don’t have to create this object...
flask.api.index#flask.Response
accept_ranges The Accept-Ranges header. Even though the name would indicate that multiple values are supported, it must be one string token only. The values 'bytes' and 'none' are common. Changelog New in version 0.7.
flask.api.index#flask.Response.accept_ranges
access_control_allow_headers Which headers can be sent with the cross origin request.
flask.api.index#flask.Response.access_control_allow_headers
access_control_allow_methods Which methods can be used for the cross origin request.
flask.api.index#flask.Response.access_control_allow_methods
access_control_allow_origin The origin or ‘*’ for any origin that may make cross origin requests.
flask.api.index#flask.Response.access_control_allow_origin
access_control_expose_headers Which headers can be shared by the browser to JavaScript code.
flask.api.index#flask.Response.access_control_expose_headers
access_control_max_age The maximum age in seconds the access control settings can be cached for.
flask.api.index#flask.Response.access_control_max_age
add_etag(overwrite=False, weak=False) Add an etag for the current response if there is none yet. Changed in version 2.0: SHA-1 is used to generate the value. MD5 may not be available in some environments. Parameters overwrite (bool) – weak (bool) – Return type None
flask.api.index#flask.Response.add_etag
age The Age response-header field conveys the sender’s estimate of the amount of time since the response (or its revalidation) was generated at the origin server. Age values are non-negative decimal integers, representing time in seconds.
flask.api.index#flask.Response.age
calculate_content_length() Returns the content length if available or None otherwise. Return type Optional[int]
flask.api.index#flask.Response.calculate_content_length