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 can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible. Flask won’t make many decisions for you, such as what database to use. Those decisions that it does make, such as what templating engine to use, are easy to change. Everything else is up to you, so that Flask can be everything you need and nothing you don’t. By default, Flask does not include a database abstraction layer, form validation or anything else where different libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your application as if it was implemented in Flask itself. Numerous extensions provide database integration, form validation, upload handling, various open authentication technologies, and more. Flask may be “micro”, but it’s ready for production use on a variety of needs. Configuration and Conventions Flask has many configuration values, with sensible defaults, and a few conventions when getting started. By convention, templates and static files are stored in subdirectories within the application’s Python source tree, with the names templates and static respectively. While this can be changed, you usually don’t have to, especially when getting started. Growing with Flask Once you have Flask up and running, you’ll find a variety of extensions available in the community to integrate your project for production. As your codebase grows, you are free to make the design decisions appropriate for your project. Flask will continue to provide a very simple glue layer to the best that Python has to offer. You can implement advanced patterns in SQLAlchemy or another database tool, introduce non-relational data persistence as appropriate, and take advantage of framework-agnostic tools built for WSGI, the Python web interface. Flask includes many hooks to customize its behavior. Should you need more customization, the Flask class is built for subclassing. If you are interested in that, check out the Becoming Big chapter. If you are curious about the Flask design principles, head over to the section about Design Decisions in Flask.
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 be a list of tuples in the form (category, message) instead. Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct: with_categories controls whether categories are returned with message text (True gives a tuple, where False gives just the message text). category_filter filters the messages down to only those matching the provided categories. See Message Flashing for examples. Changelog Changed in version 0.9: category_filter parameter added. Changed in version 0.3: with_categories parameter added. Parameters with_categories (bool) – set to True to also receive categories. category_filter (Iterable[str]) – filter of categories to limit return values. Only categories in the list will be returned. Return type Union[List[str], List[Tuple[str, str]]]
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 this from Python code like this: hello = get_template_attribute('_cider.html', 'hello') return hello('World') Changelog New in version 0.2. Parameters template_name (str) – the name of the template attribute (str) – the name of the variable of macro to access Return type Any
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, 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 or 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 Changelog New in version 0.7. Return type bool
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 language that renders the pages your application serves. MarkupSafe comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks. ItsDangerous securely signs data to ensure its integrity. This is used to protect Flask’s session cookie. Click is a framework for writing command line applications. It provides the flask command and allows adding custom management commands. Optional dependencies These distributions will not be installed automatically. Flask will detect and use them if you install them. Blinker provides support for Signals. python-dotenv enables support for Environment Variables From dotenv when running flask commands. Watchdog provides a faster, more efficient reloader for the development server. Virtual environments Use a virtual environment to manage the dependencies for your project, both in development and in production. What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project. Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages. Python comes bundled with the venv module to create virtual environments. Create an environment Create a project folder and a venv folder within: macOS/LinuxWindows $ mkdir myproject $ cd myproject $ python3 -m venv venv > mkdir myproject > cd myproject > py -3 -m venv venv Activate the environment Before you work on your project, activate the corresponding environment: macOS/LinuxWindows $ . venv/bin/activate > venv\Scripts\activate Your shell prompt will change to show the name of the activated environment. Install Flask Within the activated environment, use the following command to install Flask: $ pip install Flask Flask is now installed. Check out the Quickstart or go to the Documentation Overview.
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_decoder to override the default.
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 strings. This is the same as the HTTP date format. uuid.UUID is serialized to a string. dataclasses.dataclass is passed to dataclasses.asdict(). Markup (or any object with a __html__ method) will call the __html__ method to get a string. Assign a subclass of this to flask.Flask.json_encoder or flask.Blueprint.json_encoder to override the default. 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(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 of values. jsonify(1, 2, 3) is the same as jsonify([1, 2, 3]). Keyword arguments: Treated as a dict of values. jsonify(data=data, errors=errors) is the same as jsonify({"data": data, "errors": errors}). Passing both arguments and keyword arguments is not allowed as it’s not clear what should happen. from flask import jsonify @app.route("/users/me") def get_current_user(): return jsonify( username=g.user.username, email=g.user.email, id=g.user.id, ) Will return a JSON response like this: { "username": "admin", "email": "admin@localhost", "id": 42 } The default output omits indents and spaces after separators. In debug mode or if JSONIFY_PRETTYPRINT_REGULAR is True, the output will be formatted to be easier to read. Changelog Changed in version 0.11: Added support for serializing top-level arrays. This introduces a security risk in ancient browsers. See JSON Security. New in version 0.2. Parameters args (Any) – kwargs (Any) – Return type Response
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] = None The tag to mark the serialized object with. If None, this tag is only used as an intermediate step during tagging. tag(value) Convert the value to a valid JSON type and add the tag structure around it. Parameters value (Any) – Return type Any 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 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
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 of the active app context or defaults. kwargs (Any) – Extra arguments passed to json.load(). Return type Any Changed in version 2.0: encoding is deprecated and will be removed in Flask 2.1. The file must be text mode, or binary mode with UTF-8 bytes.
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 context or defaults. kwargs (Any) – Extra arguments passed to json.loads(). Return type Any Changed in version 2.0: encoding is deprecated and will be removed in Flask 2.1. The data must be a string or UTF-8 bytes. Changelog Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.
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 location instead of searching. Returns True if a file was loaded. Changed in version 2.0: When loading the env files, set the default encoding to UTF-8. Changelog Changed in version 1.1.0: Returns False when python-dotenv is not installed, or when the given path isn’t a file. New in version 1.0.
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_password(request.form['password']): login_user(user) app.logger.info('%s logged in successfully', user.username) return redirect(url_for('index')) else: app.logger.info('%s failed to log in', user.username) abort(401) If you don’t configure logging, Python’s default log level is usually ‘warning’. Nothing below the configured level will be visible. Basic Configuration When you want to configure logging for your project, you should do it as soon as possible when the program starts. If app.logger is accessed before logging is configured, it will add a default handler. If possible, configure logging before creating the application object. This example uses dictConfig() to create a logging configuration similar to Flask’s default, except for all logs: from logging.config import dictConfig dictConfig({ 'version': 1, 'formatters': {'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', }}, 'handlers': {'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' }}, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] } }) app = Flask(__name__) Default Configuration If you do not configure logging yourself, Flask will add a StreamHandler to app.logger automatically. During requests, it will write to the stream specified by the WSGI server in environ['wsgi.errors'] (which is usually sys.stderr). Outside a request, it will log to sys.stderr. Removing the Default Handler If you configured logging after accessing app.logger, and need to remove the default handler, you can import and remove it: from flask.logging import default_handler app.logger.removeHandler(default_handler) Email Errors to Admins When running the application on a remote server for production, you probably won’t be looking at the log messages very often. The WSGI server will probably send log messages to a file, and you’ll only check that file if a user tells you something went wrong. To be proactive about discovering and fixing bugs, you can configure a logging.handlers.SMTPHandler to send an email when errors and higher are logged. import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler( mailhost='127.0.0.1', fromaddr='[email protected]', toaddrs=['[email protected]'], subject='Application Error' ) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(logging.Formatter( '[%(asctime)s] %(levelname)s in %(module)s: %(message)s' )) if not app.debug: app.logger.addHandler(mail_handler) This requires that you have an SMTP server set up on the same server. See the Python docs for more information about configuring the handler. Injecting Request Information Seeing more information about the request, such as the IP address, may help debugging some errors. You can subclass logging.Formatter to inject your own fields that can be used in messages. You can change the formatter for Flask’s default handler, the mail handler defined above, or any other handler. from flask import has_request_context, request from flask.logging import default_handler class RequestFormatter(logging.Formatter): def format(self, record): if has_request_context(): record.url = request.url record.remote_addr = request.remote_addr else: record.url = None record.remote_addr = None return super().format(record) formatter = RequestFormatter( '[%(asctime)s] %(remote_addr)s requested %(url)s\n' '%(levelname)s in %(module)s: %(message)s' ) default_handler.setFormatter(formatter) mail_handler.setFormatter(formatter) Other Libraries Other libraries may use logging extensively, and you want to see relevant messages from those logs too. The simplest way to do this is to add handlers to the root logger instead of only the app logger. from flask.logging import default_handler root = logging.getLogger() root.addHandler(default_handler) root.addHandler(mail_handler) Depending on your project, it may be more useful to configure each logger you care about separately, instead of configuring only the root logger. for logger in ( app.logger, logging.getLogger('sqlalchemy'), logging.getLogger('other_package'), ): logger.addHandler(default_handler) logger.addHandler(mail_handler) Werkzeug Werkzeug logs basic request/response information to the 'werkzeug' logger. If the root logger has no handlers configured, Werkzeug adds a StreamHandler to its logger. Flask Extensions Depending on the situation, an extension may choose to log to app.logger or its own named logger. Consult each extension’s documentation for details.
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 and 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 a view function. This for example creates a response with a 404 error code: response = make_response(render_template('not_found.html'), 404) The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators: 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() is invoked with it. if more than one argument is passed, the arguments are passed to the flask.Flask.make_response() function as tuple. Changelog New in version 0.6. Parameters args (Any) – Return type Response
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, use the escape() class method instead. >>> Markup("Hello, <em>World</em>!") Markup('Hello, <em>World</em>!') >>> Markup(42) Markup('42') >>> Markup.escape("Hello, <em>World</em>!") Markup('Hello &lt;em&gt;World&lt;/em&gt;!') This implements the __html__() interface that some frameworks use. Passing an object that implements __html__() will wrap the output of that method, marking it safe. >>> class Foo: ... def __html__(self): ... return '<a href="/foo">foo</a>' ... >>> Markup(Foo()) Markup('<a href="/foo">foo</a>') This is a subclass of str. It has the same methods, but escapes their arguments and returns a Markup instance. >>> Markup("<em>%s</em>") % ("foo & bar",) Markup('<em>foo &amp; bar</em>') >>> Markup("<em>Hello</em> ") + "<foo>" Markup('<em>Hello</em> &lt;foo&gt;') Parameters base (Any) – encoding (Optional[str]) – errors (str) – Return type 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 striptags() unescape() the markup, remove tags, and normalize whitespace to single spaces. >>> Markup("Main &raquo; <em>About</em>").striptags() 'Main » About' Return type str 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
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): session['counter'] = session.get('counter', 0) + 1 return 'OK' app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter')) 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], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
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], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
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 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(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) (2678400 seconds)
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>Hello, World!</p>" So what did that code do? First we imported the Flask class. An instance of this class will be our WSGI application. Next we create an instance of this class. The first argument is the name of the application’s module or package. __name__ is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files. We then use the route() decorator to tell Flask what URL should trigger our function. The function returns the message we want to display in the user’s browser. The default content type is HTML, so HTML in the string will be rendered by the browser. Save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself. To run the application, use the flask command or python -m flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable: BashCMDPowershell $ export FLASK_APP=hello $ flask run * Running on http://127.0.0.1:5000/ > set FLASK_APP=hello > flask run * Running on http://127.0.0.1:5000/ > $env:FLASK_APP = "hello" > flask run * Running on http://127.0.0.1:5000/ Application Discovery Behavior As a shortcut, if the file is named app.py or wsgi.py, you don’t have to set the FLASK_APP environment variable. See Command Line Interface for more details. This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see Deployment Options. Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting. Externally Visible Server If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line: $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs. What to do if the Server does not Start In case the python -m flask fails or flask does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message. Old Version of Flask Versions of Flask older than 0.11 used to have different ways to start the application. In short, the flask command did not exist, and neither did python -m flask. In that case you have two options: either upgrade to newer Flask versions or have a look at Development Server to see the alternative method for running a server. Invalid Import Name The FLASK_APP environment variable is the name of the module to import at flask run. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed. The most common reason is a typo or because you did not actually create an app object. Debug Mode The flask run command can do more than just start the development server. By enabling debug mode, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request. Warning The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment. To enable all development features, set the FLASK_ENV environment variable to development before calling flask run. BashCMDPowershell $ export FLASK_ENV=development $ flask run > set FLASK_ENV=development > flask run > $env:FLASK_ENV = "development" > flask run See also: Development Server and Command Line Interface for information about running in development mode. Debugging Application Errors for information about using the built-in debugger and other debuggers. Logging and Handling Application Errors to log errors and display nice error pages. HTML Escaping When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. HTML templates rendered with Jinja, introduced later, will do this automatically. escape(), shown here, can be used manually. It is omitted in most examples for brevity, but you should always be aware of how you’re using untrusted data. from markupsafe import escape @app.route("/<name>") def hello(name): return f"Hello, {escape(name)}!" If a user managed to submit the name <script>alert("bad")</script>, escaping causes it to be rendered as text, rather than running the script in the user’s browser. <name> in the route captures a value from the URL and passes it to the view function. These variable rules are explained below. Routing Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page. Use the route() decorator to bind a function to a URL. @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' You can do more! You can make parts of the URL dynamic and attach multiple rules to a function. Variable Rules You can add variable sections to a URL by marking sections with <variable_name>. Your function then receives the <variable_name> as a keyword argument. Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>. from markupsafe import escape @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return f'User {username}' @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return f'Post {post_id}' @app.route('/path/<path:subpath>') def show_subpath(subpath): # show the subpath after /path/ return f'Subpath {subpath}' Converter types: string (default) accepts any text without a slash int accepts positive integers float accepts positive floating point values path like string but also accepts slashes uuid accepts UUID strings Unique URLs / Redirection Behavior The following two rules differ in their use of a trailing slash. @app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page' The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash (/projects), Flask redirects you to the canonical URL with the trailing slash (/projects/). The canonical URL for the about endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash (/about/) produces a 404 “Not Found” error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice. URL Building To build a URL to a specific function, use the url_for() function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters. Why would you want to build URLs using the URL reversing function url_for() instead of hard-coding them into your templates? Reversing is often more descriptive than hard-coding the URLs. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs. URL building handles escaping of special characters transparently. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers. If your application is placed outside the URL root, for example, in /myapplication instead of /, url_for() properly handles that for you. For example, here we use the test_request_context() method to try out url_for(). test_request_context() tells Flask to behave as though it’s handling a request even while we use a Python shell. See Context Locals. from flask import url_for @app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user/<username>') def profile(username): return f'{username}\'s profile' with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) / /login /login?next=/ /user/John%20Doe HTTP Methods Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods. from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form() If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC. Likewise, OPTIONS is automatically implemented for you. Static Files Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application. To generate URLs for static files, use the special 'static' endpoint name: url_for('static', filename='style.css') The file has to be stored on the filesystem as static/style.css. Rendering Templates Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the Jinja2 template engine for you automatically. To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template: from flask import render_template @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name) Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: Case 1: a module: /application.py /templates /hello.html Case 2: a package: /application /__init__.py /templates /hello.html For templates you can use the full power of Jinja2 templates. Head over to the official Jinja2 Template Documentation for more information. Here is an example template: <!doctype html> <title>Hello from Flask</title> {% if name %} <h1>Hello {{ name }}!</h1> {% else %} <h1>Hello, World!</h1> {% endif %} Inside templates you also have access to the request, session and g 1 objects as well as the get_flashed_messages() function. Templates are especially useful if inheritance is used. If you want to know how that works, see Template Inheritance. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer). Automatic escaping is enabled, so if name contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the Markup class or by using the |safe filter in the template. Head over to the Jinja 2 documentation for more examples. Here is a basic introduction to how the Markup class works: >>> from markupsafe import Markup >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>' Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>') >>> Markup.escape('<blink>hacker</blink>') Markup('&lt;blink&gt;hacker&lt;/blink&gt;') >>> Markup('<em>Marked up</em> &raquo; HTML').striptags() 'Marked up \xbb HTML' Changelog Changed in version 0.5: Autoescaping is no longer enabled for all templates. The following extensions for templates trigger autoescaping: .html, .htm, .xml, .xhtml. Templates loaded from a string will have autoescaping disabled. 1 Unsure what that g object is? It’s something in which you can store information for your own needs. See the documentation for flask.g and Using SQLite 3 with Flask. Accessing Request Data For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals: Context Locals Insider Information If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it. Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand. Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking. So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the test_request_context() context manager. In combination with the with statement it will bind a test request so that you can interact with it. Here is an example: from flask import request with app.test_request_context('/hello', method='POST'): # now you can do something with the request until the # end of the with block, such as basic assertions: assert request.path == '/hello' assert request.method == 'POST' The other possibility is passing a whole WSGI environment to the request_context() method: with app.request_context(environ): assert request.method == 'POST' The Request Object The request object is documented in the API section and we will not cover it here in detail (see Request). Here is a broad overview of some of the most common operations. First of all you have to import it from the flask module: from flask import request The current request method is available by using the method attribute. To access form data (data transmitted in a POST or PUT request) you can use the form attribute. Here is a full example of the two attributes mentioned above: @app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error) What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem. To access parameters submitted in the URL (?key=value) you can use the args attribute: searchword = request.args.get('key', '') We recommend accessing URL parameters with get or by catching the KeyError because users might change the URL and presenting them a 400 bad request page in that case is not user friendly. For a full list of methods and attributes of the request object, head over to the Request documentation. File Uploads You can handle uploaded files with Flask easily. Just make sure not to forget to set the enctype="multipart/form-data" attribute on your HTML form, otherwise the browser will not transmit your files at all. Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works: from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ... If you want to know how the file was named on the client before it was uploaded to your application, you can access the filename attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the secure_filename() function that Werkzeug provides for you: from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['the_file'] file.save(f"/var/www/uploads/{secure_filename(f.filename)}") ... For some better examples, see Uploading Files. Cookies To access cookies you can use the cookies attribute. To set cookies you can use the set_cookie method of response objects. The cookies attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the Sessions in Flask that add some security on top of cookies for you. Reading cookies: from flask import request @app.route('/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing. Storing cookies: from flask import make_response @app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the make_response() function and then modify it. Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the Deferred Request Callbacks pattern. For this also see About Responses. Redirects and Errors To redirect a user to another endpoint, use the redirect() function; to abort a request early with an error code, use the abort() function: from flask import abort, redirect, url_for @app.route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): abort(401) this_is_never_executed() This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works. By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the errorhandler() decorator: from flask import render_template @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 Note the 404 after the render_template() call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well. See Handling Application Errors for more details. About Responses The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a 200 OK status code and a text/html mimetype. If the return value is a dict, jsonify() is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows: If a response object of the correct type is returned it’s directly returned from the view. If it’s a string, a response object is created with that data and the default parameters. If it’s a dict, a response object is created using jsonify. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status), (response, headers), or (response, status, headers). The status value will override the status code and headers can be a list or dictionary of additional header values. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object. If you want to get hold of the resulting response object inside the view you can use the make_response() function. Imagine you have a view like this: from flask import render_template @app.errorhandler(404) def not_found(error): return render_template('error.html'), 404 You just need to wrap the return expression with make_response() and get the response object to modify it, then return it: from flask import make_response @app.errorhandler(404) def not_found(error): resp = make_response(render_template('error.html'), 404) resp.headers['X-Something'] = 'A value' return resp APIs with JSON A common response format when writing an API is JSON. It’s easy to get started writing such an API with Flask. If you return a dict from a view, it will be converted to a JSON response. @app.route("/me") def me_api(): user = get_current_user() return { "username": user.username, "theme": user.theme, "image": url_for("user_image", filename=user.image), } Depending on your API design, you may want to create JSON responses for types other than dict. In that case, use the jsonify() function, which will serialize any supported JSON data type. Or look into Flask community extensions that support more complex applications. from flask import jsonify @app.route("/users") def users_api(): users = get_all_users() return jsonify([user.to_json() for user in users]) Sessions In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing. In order to use sessions you have to set a secret key. Here is how sessions work: from flask import session # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/') def index(): if 'username' in session: return f'Logged in as {session["username"]}' return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) How to generate good secret keys A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret_key (or SECRET_KEY): $ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers. Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this. Message Flashing Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message. To flash a message use the flash() method, to get hold of the messages you can use get_flashed_messages() which is also available in the templates. See Message Flashing for a full example. Logging Changelog New in version 0.3. Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with 400 Bad Request in that situation, but sometimes that won’t do and the code has to continue working. You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use. Here are some example log calls: app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') The attached logger is a standard logging Logger, so head over to the official logging docs for more information. See Handling Application Errors. Hooking in WSGI Middleware To add WSGI middleware to your Flask application, wrap the application’s wsgi_app attribute. For example, to apply Werkzeug’s ProxyFix middleware for running behind Nginx: from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) Wrapping app.wsgi_app instead of app means that app still points at your Flask application, not at the middleware, so you can continue to use and configure app directly. Using Flask Extensions Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask. For more on Flask extensions, see Extensions. Deploying to a Web Server Ready to deploy your new Flask app? See Deployment Options.
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 a request with defined If-Modified-Since headers. Changelog New in version 0.10: The class used for the Response object can now be passed in. New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function. Parameters location (str) – the location the response should redirect to. code (int) – the redirect status code. defaults to 302. Response (class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified. Return type Response
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) – the variables that should be available in the context of the template. Return type str
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 of the template. Return type str
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 object is a Request subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones. Parameters environ (WSGIEnvironment) – populate_request (bool) – shallow (bool) – Return type None property accept_charsets: werkzeug.datastructures.CharsetAccept List of charsets this client supports as CharsetAccept object. property accept_encodings: werkzeug.datastructures.Accept List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset. property accept_languages: werkzeug.datastructures.LanguageAccept List of languages this client accepts as LanguageAccept object. property accept_mimetypes: werkzeug.datastructures.MIMEAccept List of mimetypes this client supports as MIMEAccept object. 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. 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. property access_route: List[str] If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server. 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): return Response('Hello World!') As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing. Parameters f (Callable[[Request], WSGIApplication]) – the WSGI callable to decorate Returns a new WSGI callable Return type WSGIApplication property args: MultiDict[str, str] The parsed URL parameters (the part in the URL after the question mark). By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important. property authorization: Optional[werkzeug.datastructures.Authorization] The Authorization object in parsed form. property base_url: str Like url but without the query string. property blueprint: Optional[str] The name of the current blueprint property cache_control: werkzeug.datastructures.RequestCacheControl A RequestCacheControl object for the incoming cache control headers. 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 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 header field. Changelog New in version 0.9. property content_length: Optional[int] The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET. 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 malicious attacks.) Changelog New in version 0.9. 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. property cookies: ImmutableMultiDict[str, str] A dict with the contents of all cookies transmitted with the request. property data: bytes Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle. 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. dict_storage_class alias of werkzeug.datastructures.ImmutableMultiDict property endpoint: Optional[str] The endpoint that matched the request. This in combination with view_args can be used to reconstruct the same or a modified URL. If an exception happened when matching, this will be None. environ: WSGIEnvironment The WSGI environment containing HTTP headers and information from the WSGI server. property files: ImmutableMultiDict[str, FileStorage] MultiDict object containing all uploaded files. Each key in files is the name from the <input type="file" name="">. Each value in files is a Werkzeug FileStorage object. It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem. Note that files will only contain data if the request method was POST, PUT or PATCH and the <form> that posted to the request had enctype="multipart/form-data". It will be empty otherwise. See the MultiDict / FileStorage documentation for more details about the used data structure. property form: ImmutableMultiDict[str, str] The form parameters. By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important. Please keep in mind that file uploads will not end up here, but instead in the files attribute. Changelog Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests. form_data_parser_class alias of werkzeug.formparser.FormDataParser 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 object (Client) that allows to create multipart requests, support for cookies etc. This accepts the same options as the EnvironBuilder. Changelog Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides. Returns request object Parameters args (Any) – kwargs (Any) – Return type werkzeug.wrappers.request.Request property full_path: str Requested path, including the query string. 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 client could send dozens of megabytes or more to cause memory problems on the server. Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory. If as_text is set to True the return value will be a decoded string. Changelog New in version 0.9. Parameters cache (bool) – as_text (bool) – parse_form_data (bool) – Return type Union[bytes, str] 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 always try to parse JSON. silent (bool) – Silence parsing errors and return None instead. cache (bool) – Store the parsed JSON to return for subsequent calls. Return type Optional[Any] headers The headers received with the request. property host: str The host name the request was made to, including the port if it’s non-standard. Validated with trusted_hosts. property host_url: str The request URL scheme and host only. property if_match: werkzeug.datastructures.ETags An object containing all the etags in the If-Match header. Return type ETags property if_modified_since: Optional[datetime.datetime] The parsed If-Modified-Since header as a datetime object. Changed in version 2.0: The datetime object is timezone-aware. property if_none_match: werkzeug.datastructures.ETags An object containing all the etags in the If-None-Match header. Return type ETags property if_range: werkzeug.datastructures.IfRange The parsed If-Range header. Changed in version 2.0: IfRange.date is timezone-aware. Changelog New in version 0.7. property if_unmodified_since: Optional[datetime.datetime] The parsed If-Unmodified-Since header as a datetime object. Changed in version 2.0: The datetime object is timezone-aware. 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. property is_json: bool Check if the mimetype indicates JSON data, either application/json or application/*+json. is_multiprocess boolean that is True if the application is served by a WSGI server that spawns multiple processes. is_multithread boolean that is True if the application is served by a multithreaded WSGI server. 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. property is_secure: bool True if the request was made with a secure protocol (HTTPS or WSS). property json: Optional[Any] The parsed JSON data if mimetype indicates JSON (application/json, see is_json()). Calls get_json() with default arguments. list_storage_class alias of werkzeug.datastructures.ImmutableList 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 property max_content_length: Optional[int] Read-only view of the MAX_CONTENT_LENGTH config key. 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. method The method the request was made with, such as GET. property mimetype: str Like content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is text/HTML; charset=utf-8 the mimetype would be 'text/html'. property mimetype_params: Dict[str, str] The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}. 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 origin The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed. parameter_storage_class alias of werkzeug.datastructures.ImmutableMultiDict path The path part of the URL after root_path. This is the path used for routing within the application. property pragma: werkzeug.datastructures.HeaderSet The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives. query_string The part of the URL after the “?”. This is the raw value, use args for the parsed values. property range: Optional[werkzeug.datastructures.Range] The parsed Range header. Changelog New in version 0.7. Return type Range 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). remote_addr The address of the client sending the request. remote_user If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as. root_path The prefix that the application is mounted under, without a trailing slash. path comes after this. property root_url: str The request URL scheme, host, and root path. This is the root that the application is accessed from. 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. scheme The URL scheme of the protocol the request used, such as https or wss. property script_root: str Alias for self.root_path. environ["SCRIPT_ROOT"] without a trailing slash. server The address of the server. (host, port), (path, None) for unix sockets, or None if not known. 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. property stream: BinaryIO If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use data which will give you that data as a string. The stream only returns the data once. Unlike input_stream this stream is properly guarded that you can’t accidentally read past the length of the input. Werkzeug will internally always refer to this stream to read data which makes it possible to wrap this object with a stream that does filtering. Changelog Changed in version 0.9: This stream is now always available but might be consumed by the form parser later on. Previously the stream was only set if no parsing happened. property url: str The full request URL with the scheme, host, root path, path, and query string. property url_charset: str The charset that is assumed for URLs. Defaults to the value of charset. Changelog New in version 0.6. property url_root: str Alias for root_url. The URL with scheme, host, and root path. For example, https://example.com/app/. 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.valid_methods instead (an attribute of the Werkzeug exception MethodNotAllowed) because the request was never internally bound. Changelog New in version 0.6. property user_agent: werkzeug.user_agent.UserAgent The user agent. Use user_agent.string to get the header value. Set user_agent_class to a subclass of UserAgent to provide parsing for the other properties or other extended data. Changed in version 2.0: The built in parser is deprecated and will be removed in Werkzeug 2.1. A UserAgent subclass must be set to parse data from the string. user_agent_class alias of werkzeug.useragents._UserAgent property values: CombinedMultiDict[str, str] A werkzeug.datastructures.CombinedMultiDict that combines args and form. For GET requests, only args are present, not form. Changed in version 2.0: For GET requests, only args are present, not form. 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. property want_form_data_parsed: bool True if the request method carries content. By default this is true if a Content-Type is sent. Changelog New in version 0.8.
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): return Response('Hello World!') As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing. Parameters f (Callable[[Request], WSGIApplication]) – the WSGI callable to decorate Returns a new WSGI callable Return type WSGIApplication
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 header field. Changelog New in version 0.9.
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 malicious attacks.) Changelog New in version 0.9.
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 object (Client) that allows to create multipart requests, support for cookies etc. This accepts the same options as the EnvironBuilder. Changelog Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides. Returns request object Parameters args (Any) – kwargs (Any) – Return type werkzeug.wrappers.request.Request
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 client could send dozens of megabytes or more to cause memory problems on the server. Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory. If as_text is set to True the return value will be a decoded string. Changelog New in version 0.9. Parameters cache (bool) – as_text (bool) – parse_form_data (bool) – Return type Union[bytes, str]
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 always try to parse JSON. silent (bool) – Silence parsing errors and return None instead. cache (bool) – Store the parsed JSON to return for subsequent calls. Return type Optional[Any]
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.valid_methods instead (an attribute of the Werkzeug exception MethodNotAllowed) because the request was never internally bound. Changelog New in version 0.6.
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 environment provided. Do not attempt to use this class directly, instead use test_request_context() and request_context() to create this object. When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (teardown_request()). The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of DEBUG mode. By setting 'flask._preserve_context' to True on the WSGI environment the context will not pop itself at the end of the request. This is used by the test_client() for example to implement the deferred cleanup functionality. You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly pop() the stack yourself in that situation, otherwise your unittests will leak memory. Parameters app (Flask) – environ (dict) – request (Optional[Request]) – session (Optional[SessionMixin]) – Return type None 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 Changed in version 1.1: The current session object is used instead of reloading the original data. This prevents flask.session pointing to an out-of-date object. New in version 0.10. Return type flask.ctx.RequestContext match_request() Can be overridden by a subclass to hook into the matching of the request. Return type None 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 push() Binds the request context to the current context. Return type None
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 Changed in version 1.1: The current session object is used instead of reloading the original data. This prevents flask.session pointing to an out-of-date object. New in version 0.10. Return type flask.ctx.RequestContext
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 yourself because make_response() will take care of that for you. If you want to replace the response object used you can subclass this and set response_class to your subclass. Changelog Changed in version 1.0: JSON support is added to the response, like the request. This is useful when testing to get the test client response data as JSON. Changed in version 1.0: Added max_cookie_size. Parameters response (Union[Iterable[str], Iterable[bytes]]) – status (Optional[Union[int, str, http.HTTPStatus]]) – headers (werkzeug.datastructures.Headers) – mimetype (Optional[str]) – content_type (Optional[str]) – direct_passthrough (bool) – Return type None 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. property access_control_allow_credentials: bool Whether credentials can be shared by the browser to JavaScript code. As part of the preflight request it indicates whether credentials can be used on the cross origin request. access_control_allow_headers Which headers can be sent with the cross origin request. access_control_allow_methods Which methods can be used for the cross origin request. access_control_allow_origin The origin or ‘*’ for any origin that may make cross origin requests. access_control_expose_headers Which headers can be shared by the browser to JavaScript code. access_control_max_age The maximum age in seconds the access control settings can be cached for. 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 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. property allow: werkzeug.datastructures.HeaderSet The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The purpose of this field is strictly to inform the recipient of valid methods associated with the resource. An Allow header field MUST be present in a 405 (Method Not Allowed) response. property cache_control: werkzeug.datastructures.ResponseCacheControl The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain. calculate_content_length() Returns the content length if available or None otherwise. Return type Optional[int] call_on_close(func) Adds a function to the internal list of functions that should be called as part of closing down the response. Since 0.7 this function also returns the function that was passed so that this can be used as a decorator. Changelog New in version 0.6. Parameters func (Callable[[], Any]) – Return type Callable[[], Any] close() Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it. Changelog New in version 0.9: Can now be used in a with statement. Return type None 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 header field. property content_language: werkzeug.datastructures.HeaderSet The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body. content_length The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET. content_location The Content-Location entity-header field MAY be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource’s URI. 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 malicious attacks.) property content_range: werkzeug.datastructures.ContentRange The Content-Range header as a ContentRange object. Available even if the header is not set. Changelog New in version 0.7. content_security_policy The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks. content_security_policy_report_only The Content-Security-Policy-Report-Only header adds a csp policy that is not enforced but is reported thereby helping detect certain types of attacks. 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. cross_origin_embedder_policy Prevents a document from loading any cross-origin resources that do not explicitly grant the document permission. Values must be a member of the werkzeug.http.COEP enum. cross_origin_opener_policy Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the werkzeug.http.COOP enum. property data: Union[bytes, str] A descriptor that calls get_data() and set_data(). 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. delete_cookie(key, path='/', domain=None, secure=False, httponly=False, samesite=None) Delete a cookie. Fails silently if key doesn’t exist. Parameters key (str) – the key (name) of the cookie to be deleted. path (str) – if the cookie that should be deleted was limited to a path, the path has to be defined here. domain (Optional[str]) – if the cookie that should be deleted was limited to a domain, that domain has to be defined here. secure (bool) – If True, the cookie will only be available via HTTPS. httponly (bool) – Disallow JavaScript access to the cookie. samesite (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”. Return type None direct_passthrough Pass the response body directly through as the WSGI iterable. This can be used when the body is a binary file or other iterator of bytes, to skip some unnecessary checks. Use send_file() instead of setting this manually. expires The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache. Changed in version 2.0: The datetime object is timezone-aware. classmethod force_type(response, environ=None) Enforce that the WSGI response is a response object of the current type. Werkzeug will use the Response internally in many situations like the exceptions. If you call get_response() on an exception you will get back a regular Response object, even if you are using a custom subclass. This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided: # convert a Werkzeug response object into an instance of the # MyResponseClass subclass. response = MyResponseClass.force_type(response) # convert any WSGI application into a response object response = MyResponseClass.force_type(response, environ) This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass. Keep in mind that this will modify response objects in place if possible! Parameters response (Response) – a response object or wsgi application. environ (Optional[WSGIEnvironment]) – a WSGI environment object. Returns a response object. Return type Response freeze(no_etag=None) Make the response object ready to be pickled. Does the following: Buffer the response into a list, ignoring implicity_sequence_conversion and direct_passthrough. Set the Content-Length header. Generate an ETag header if one is not already set. Changed in version 2.0: An ETag header is added, the no_etag parameter is deprecated and will be removed in Werkzeug 2.1. Changelog Changed in version 0.6: The Content-Length header is set. Parameters no_etag (None) – Return type None classmethod from_app(app, environ, buffered=False) Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the write() callable returned by the start_response function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set buffered to True which enforces buffering. Parameters app (WSGIApplication) – the WSGI application to execute. environ (WSGIEnvironment) – the WSGI environment to execute against. buffered (bool) – set to True to enforce buffering. Returns a response object. Return type Response get_app_iter(environ) Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is HEAD or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. Changelog New in version 0.6. Parameters environ (WSGIEnvironment) – the WSGI environment of the request. Returns a response iterable. Return type Iterable[bytes] get_data(as_text=False) The string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting implicit_sequence_conversion to False. If as_text is set to True the return value will be a decoded string. Changelog New in version 0.9. Parameters as_text (bool) – Return type Union[bytes, str] get_etag() Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None). Return type Union[Tuple[str, bool], Tuple[None, None]] get_json(force=False, silent=False) Parse data as JSON. Useful during testing. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. Unlike Request.get_json(), the result is not cached. Parameters force (bool) – Ignore the mimetype and always try to parse JSON. silent (bool) – Silence parsing errors and return None instead. Return type Optional[Any] get_wsgi_headers(environ) This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the location header (if present) is joined with the root URL of the environment. Also the content length is automatically set to zero here for certain status codes. Changelog Changed in version 0.6: Previously that function was called fix_headers and modified the response object in place. Also since 0.6, IRIs in location and content-location headers are handled properly. Also starting with 0.6, Werkzeug will attempt to set the content length if it is able to figure it out on its own. This is the case if all the strings in the response iterable are already encoded and the iterable is buffered. Parameters environ (WSGIEnvironment) – the WSGI environment of the request. Returns returns a new Headers object. Return type werkzeug.datastructures.Headers get_wsgi_response(environ) Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is 'HEAD' the response will be empty and only the headers and status code will be present. Changelog New in version 0.6. Parameters environ (WSGIEnvironment) – the WSGI environment of the request. Returns an (app_iter, status, headers) tuple. Return type Tuple[Iterable[bytes], str, List[Tuple[str, str]]] property is_json: bool Check if the mimetype indicates JSON data, either application/json or application/*+json. property is_sequence: bool If the iterator is buffered, this property will be True. A response object will consider an iterator to be buffered if the response attribute is a list or tuple. Changelog New in version 0.6. property is_streamed: bool If the response is streamed (the response is not an iterable with a length information) this property is True. In this case streamed means that there is no information about the number of iterations. This is usually True if a generator is passed to the response object. This is useful for checking before applying some sort of post filtering that should not take place for streamed responses. iter_encoded() Iter the response encoded with the encoding of the response. If the response object is invoked as WSGI application the return value of this method is used as application iterator unless direct_passthrough was activated. Return type Iterator[bytes] property json: Optional[Any] The parsed JSON data if mimetype indicates JSON (application/json, see is_json()). Calls get_json() with default arguments. last_modified The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified. Changed in version 2.0: The datetime object is timezone-aware. location The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. make_conditional(request_or_environ, accept_ranges=False, complete_length=None) Make the response conditional to the request. This method works best if an etag was defined for the response already. The add_etag method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is anything but GET or HEAD. For optimal performance when handling range requests, it’s recommended that your response data object implements seekable, seek and tell methods as described by io.IOBase. Objects returned by wrap_file() automatically implement those methods. It does not remove the body of the response because that’s something the __call__() function does for us automatically. Returns self so that you can do return resp.make_conditional(req) but modifies the object in-place. Parameters request_or_environ (WSGIEnvironment) – a request object or WSGI environment to be used to make the response conditional against. accept_ranges (Union[bool, str]) – This parameter dictates the value of Accept-Ranges header. If False (default), the header is not set. If True, it will be set to "bytes". If None, it will be set to "none". If it’s a string, it will use this value. complete_length (Optional[int]) – Will be used only in valid Range Requests. It will set Content-Range complete length value and compute Content-Length real value. This parameter is mandatory for successful Range Requests completion. Raises RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied. Return type Response Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error. make_sequence() Converts the response iterator in a list. By default this happens automatically if required. If implicit_sequence_conversion is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. Changelog New in version 0.6. Return type None property max_cookie_size: int Read-only view of the MAX_COOKIE_SIZE config key. See max_cookie_size in Werkzeug’s docs. property mimetype: Optional[str] The mimetype (content type without charset etc.) property mimetype_params: Dict[str, str] The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}. Changelog New in version 0.5. property retry_after: Optional[datetime.datetime] The Retry-After response-header field can be used with a 503 (Service Unavailable) response to indicate how long the service is expected to be unavailable to the requesting client. Time in seconds until expiration or date. Changed in version 2.0: The datetime object is timezone-aware. set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None) Sets a cookie. A warning is raised if the size of the cookie header exceeds max_cookie_size, but the header will still be set. Parameters key (str) – the key (name) of the cookie to be set. value (str) – the value of the cookie. max_age (Optional[Union[datetime.timedelta, int]]) – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. expires (Optional[Union[str, datetime.datetime, int, float]]) – should be a datetime object or UNIX timestamp. path (Optional[str]) – limits the cookie to a given path, per default it will span the whole domain. domain (Optional[str]) – if you want to set a cross-domain cookie. For example, domain=".example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it. secure (bool) – If True, the cookie will only be available via HTTPS. httponly (bool) – Disallow JavaScript access to the cookie. samesite (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”. Return type None set_data(value) Sets a new string as response. The value must be a string or bytes. If a string is set it’s encoded to the charset of the response (utf-8 by default). Changelog New in version 0.9. Parameters value (Union[bytes, str]) – Return type None set_etag(etag, weak=False) Set the etag, and override the old one if there was one. Parameters etag (str) – weak (bool) – Return type None property status: str The HTTP status code as a string. property status_code: int The HTTP status code as a number. property stream: werkzeug.wrappers.response.ResponseStream The response iterable as write-only stream. property vary: werkzeug.datastructures.HeaderSet The Vary field value indicates the set of request-header fields that fully determines, while the response is fresh, whether a cache is permitted to use the response to reply to a subsequent request without revalidation. property www_authenticate: werkzeug.datastructures.WWWAuthenticate The WWW-Authenticate header in a parsed form.
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