Incoming Request Data
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)–
propertyaccept_charsets:CharsetAccept
List of charsets this client supports as CharsetAccept object.
propertyaccept_encodings: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.
propertyaccept_languages:LanguageAccept
List of languages this client accepts as LanguageAccept object.
propertyaccept_mimetypes: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.
propertyaccess_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.
classmethodapplication(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:python@Request.application def my_wsgi_app(request): return Response('Hello World!')@Request.application def my_wsgi_app(request): return Response('Hello World!')As of
Werkzeug0.14HTTPexceptions are automatically caught and converted to responses instead of failing.Parameters:
- f (
t.Callable[[Request], WSGIApplication]) – theWSGIcallable to decorate
Returns: a new
WSGIcallableReturn type:
WSGIApplication- f (
propertyargs:MultiDict[str, str]The parsed URL parameters (the part in the URL after the question mark).
By default an
ImmutableMultiDictis returned from this function. This can be changed by settingparameter_storage_classto a different type. This might be necessary if the order of the form data is important.Changed in version 2.3: Invalid bytes remain percent encoded.
propertyauthorization:Authorization | NoneThe Authorization header parsed into an Authorization object. None if the header is not present.
Changed in version 2.3: Authorization is no longer a dict. The token attribute was added for auth schemes that use a token instead of parameters.
propertybase_url:strLike url but without the query string.
propertyblueprint:str | NoneThe registered name of the current blueprint.
This will be
Noneif the endpoint is not part of a blueprint, or if URL matching failed or has not been performed yet.This does not necessarily match the name the blueprint was created with. It may have been nested, or registered with a different name.
propertyblueprints:list[str]The registered names of the current blueprint upwards through parent blueprints.
This will be an empty list if there is no current blueprint, or if URL matching failed.
Changelog
New in version 2.0.1.
propertycache_control:RequestCacheControlA
RequestCacheControlobject for the incoming cache control headers.propertycharset:strThe charset used to decode body, form, and cookie data. Defaults to
UTF-8.Deprecated since version 2.3: Will be removed in
Werkzeug3.0. Request data must always beUTF-8.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:
Nonecontent_encoding
The
Content-Encodingentity-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 theContent-Typeheader field.Changelog
New in version 0.9.
propertycontent_length:int | NoneThe
Content-Lengthentity-header field indicates the size of the entity-body in bytes or, in the case of theHEADmethod, the size of the entity-body that would have been sent had the request been aGET.content_md5
The
Content-MD5entity-header field, as defined inRFC 1864, is anMD5digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: aMICis 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-Typeentity-header field indicates the media type of the entity-body sent to the recipient or, in the case of theHEADmethod, the media type that would have been sent had the request been aGET.propertycookies:ImmutableMultiDict[str, str]A dict with the contents of all cookies transmitted with the request.
propertydata:bytesThe raw data read from stream. Will be empty if the request represents form data.
To get the raw data even if it represents form data, use
get_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.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
dict_storage_class
alias of
ImmutableMultiDictpropertyencoding_errors:strHow errors when decoding bytes are handled. Defaults to
“replace”.Deprecated since version 2.3: Will be removed in
Werkzeug3.0.propertyendpoint:str | NoneThe endpoint that matched the request URL.
This will be
Noneif matching failed or has not been performed yet.This in combination with
view_argscan be used to reconstruct the same URL or a modified URL.environ:
WSGIEnvironmentThe
WSGIenvironment containingHTTPheaders and information from theWSGIserver.propertyfiles:ImmutableMultiDict[str, FileStorage]MultiDictobject containing all uploaded files. Each key in files is the name from the<input type="file" name="">. Each value infilesis aWerkzeugFileStorageobject.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,PUTorPATCHand the<form>that posted to the request hadenctype="multipart/form-data". It will be empty otherwise.See the
MultiDict / FileStoragedocumentation for more details about the used data structure.propertyform:ImmutableMultiDict[str, str]The form parameters. By default an
ImmutableMultiDictis returned from this function. This can be changed by settingparameter_storage_classto 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
Werkzeug0.9 this would only contain form data forPOSTandPUTrequests.form_data_parser_class
alias of
FormDataParserclassmethodfrom_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 createmultipartrequests, 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 theenvironparameter is now calledenviron_overrides.Returns: request object
Parameters:
args (Any)–kwargs (Any)–
Return type:
Requestpropertyfull_path:strRequested 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_datatoTrue. 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_textis set toTruethe 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:
bytes | strget_json(
force=False, silent=False, cache=True) Parse
dataasJSON.If the
mimetypedoes not indicateJSON(application/json, seeis_json), or parsing fails,on_json_loading_failed()is called and its return value is used as the return value. By default this raises a415Unsupported Media Type resp.Parameters:
force (bool)– Ignore the mimetype and always try to parseJSON.silent (bool)– Silence mimetype and parsing errors, and returnNoneinstead.cache (bool)– Store the parsed JSON to return for subsequent calls.
Return type:
Any | NoneChanged in version 2.3: Raise a
415error instead of400.Changelog
Changed in version 2.1: Raise a
400error if the content type is incorrect.headers
The headers received with the request.
propertyhost:strThe host name the request was made to, including the port if it’s non-standard. Validated with
trusted_hosts.propertyhost_url:strThe request URL scheme and host only.
propertyif_match:ETagsAn object containing all the etags in the
If-Matchheader.Return type:
ETagspropertyif_modified_since:datetime | NoneThe parsed
If-Modified-Sinceheader as a datetime object.Changelog
Changed in version 2.0: The datetime object is timezone-aware.
propertyif_none_match:ETagsAn object containing all the etags in the
If-None-Matchheader.Return type:
ETagspropertyif_range:IfRangeThe parsed
If-Rangeheader.Changelog
Changed in version 2.0:
IfRange.dateis timezone-aware.New in version 0.7.
propertyif_unmodified_since:datetime | NoneThe parsed
If-Unmodified-Sinceheader as a datetime object.hangelog
Changed in version 2.0: The datetime object is timezone-aware.
input_stream
The raw
WSGIinput stream, without any safety checks.This is dangerous to use. It does not guard against infinite streams or reading past
content_lengthormax_content_length.Use
streaminstead.propertyis_json:boolCheck if the mimetype indicates JSON data, either
application/jsonorapplication/*+json.is_multiprocess
boolean that is
Trueif the application is served by aWSGIserver that spawns multiple processes.is_multithread
boolean that is
Trueif the application is served by a multithreadedWSGIserver.is_run_once
boolean that is
Trueif the application will be executed only once in a process lifetime. This is the case forCGIfor example, but it’s not guaranteed that the execution only happens one time.propertyis_secure:boolTrueif the request was made with a secure protocol (HTTPSorWSS).propertyjson:Any | NoneThe parsed
JSONdata ifmimetypeindicatesJSON(application/json, seeis_json).Calls
get_json()with default arguments.If the request content type is not
application/json, this will raise a415Unsupported Media Type error.Changed in version 2.3: Raise a
415error instead of400.Changelog
Changed in version 2.1: Raise a
400error if the content type is incorrect.list_storage_class
alias of
ImmutableListmake_form_data_parser()
Creates the form data parser. Instantiates the
form_data_parser_classwith some parameters.Changelog
New in version 0.8.
Return type:
FormDataParserpropertymax_content_length:int | NoneRead-only view of the
MAX_CONTENT_LENGTHconfig key.max_form_memory_size:
int | None = Nonethe maximum form field size. This is forwarded to the form data parsing function (
parse_form_data()). When set and theformorfilesattribute is accessed and the data in memory for post data is longer than the specified value aRequestEntityTooLargeexception is raised.Changelog
New in version 0.5.
max_form_parts =
1000The maximum number of multipart parts to parse, passed to
form_data_parser_class. Parsing form data with more than this many parts will raiseRequestEntityTooLarge.Changelog
New in version 2.2.3.
max_forwards
The
Max-Forwardsrequest-header field provides a mechanism with theTRACEandOPTIONSmethods 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.propertymimetype:strLike
content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type istext/HTML; charset=utf-8the mimetype would be'text/html'.propertymimetype_params:dict[str, str]The mimetype parameters as
dict. For example if the content type istext/html; charset=utf-8the params would be{'charset': 'utf-8'}.on_json_loading_failed(
e) Called if
get_json()fails and isn’t silenced.If this method returns a value, it is used as the return value for
get_json(). The default implementation raisesBadRequest.Parameters:
- e (ValueError | None) – If parsing failed, this is the exception. It will be
Noneif the content type wasn’tapplication/json.
Return type:
AnyChanged in version 2.3: Raise a
415error instead of400.- e (ValueError | None) – If parsing failed, this is the exception. It will be
origin
The host that the request originated from. Set
access_control_allow_originon the response to indicate which origins are allowed.parameter_storage_class
alias of
ImmutableMultiDictpath
The path part of the URL after
root_path. This is the path used for routing within the application.propertypragma:HeaderSetThe 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, useargsfor the parsed values.propertyrange:Range | NoneThe parsed
Rangeheader.Changelog
New in version 0.7.
Return type:
Rangereferrer
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.
pathcomes after this.propertyroot_url:strThe request URL scheme, host, and root path. This is the root that the application is accessed from.
routing_exception:
Exception | None = NoneIf matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a
NotFoundexception or something similar.scheme
The URL scheme of the protocol the request used, such as
httpsorwss.propertyscript_root:strAlias 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:
boolSet when creating the request object. If
True, reading from the request body will cause aRuntimeException. Useful to prevent modifying the stream from middleware.propertystream:IO[bytes]The
WSGIinput stream, with safety checks. This stream can only be consumed once.Use
get_data()to get the full data as bytes or text. Thedataattribute will contain the full bytes only if they do not represent form data. Theformattribute will contain the parsed form data in that case.Unlike
input_stream, this stream guards against infinite streams or reading pastcontent_lengthormax_content_length.If
max_content_lengthis set, it can be enforced on streams ifwsgi.input_terminatedis set. Otherwise, an empty stream is returned.If the limit is reached before the underlying stream is exhausted (such as a file that is too large, or an infinite stream), the remaining contents of the stream cannot be read safely. Depending on how the server handles this, clients may show a “connection reset” failure instead of seeing the
413response.Changed in version 2.3: Check
max_content_lengthpreemptively and while reading.Changelog
Changed in version 0.9: The stream is always set (but may be consumed) even if form parsing was accessed first.
trusted_hosts:
list[str] | None = NoneValid host names when handling requests. By default all hosts are trusted, which means that whatever the client says the host is will be accepted.
Because
HostandX-Forwarded-Hostheaders can be set to any value by a malicious client, it is recommended to either set this property or implement similar validation in the proxy (if the application is being run behind one).Changelog
New in version 0.9.
propertyurl:strThe full request URL with the scheme, host, root path, path, and query string.
propertyurl_charset:strThe charset to use when decoding percent-encoded bytes in
args. Defaults to the value ofcharset, which defaults toUTF-8.Deprecated since version 2.3: Will be removed in
Werkzeug3.0. Percent-encoded bytes must always beUTF-8.Changelog
New in version 0.6.
propertyurl_root:strAlias for
root_url. The URL with scheme, host, and root path. For example,https://example.com/app/.url_rule:
Rule | None = NoneThe 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 inrouting_exception.valid_methodsinstead (an attribute of the Werkzeug exceptionMethodNotAllowed) because the request was never internally bound.Changelog
New in version 0.6.
propertyuser_agent:UserAgentThe user agent. Use
user_agent.stringto get the header value. Setuser_agent_classto a subclass ofUserAgentto provide parsing for the other properties or other extended data.Changelog
Changed in version 2.1: The built-in parser was removed. Set
user_agent_classto aUserAgentsubclass to parse data from the string.user_agent_class
alias of
UserAgentpropertyvalues:CombinedMultiDict[str, str]A
werkzeug.datastructures.CombinedMultiDictthat combinesargsandform.For
GETrequests, onlyargsare present, notform.Changelog
Changed in version 2.0: For
GETrequests, onlyargsare present, notform.view_args:
dict[str, t.Any] | None = NoneA dict of view arguments that matched the request. If an exception happened when matching, this will be
None.propertywant_form_data_parsed:boolTrueif the request method carries content. By default this is true if aContent-Typeis sent.Changelog
New in version 0.8.
flask.request
To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.
This is a proxy. See Notes On Proxies for more information.
The request object is an instance of a Request.