doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
parameter_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict | werkzeug.wrappers.index#werkzeug.wrappers.Request.parameter_storage_class |
path
The path part of the URL after root_path. This is the path used for routing within the application. | werkzeug.wrappers.index#werkzeug.wrappers.Request.path |
query_string
The part of the URL after the “?”. This is the raw value, use args for the parsed values. | werkzeug.wrappers.index#werkzeug.wrappers.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). | werkzeug.wrappers.index#werkzeug.wrappers.Request.referrer |
remote_addr
The address of the client sending the request. | werkzeug.wrappers.index#werkzeug.wrappers.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. | werkzeug.wrappers.index#werkzeug.wrappers.Request.remote_user |
root_path
The prefix that the application is mounted under, without a trailing slash. path comes after this. | werkzeug.wrappers.index#werkzeug.wrappers.Request.root_path |
scheme
The URL scheme of the protocol the request used, such as https or wss. | werkzeug.wrappers.index#werkzeug.wrappers.Request.scheme |
server
The address of the server. (host, port), (path, None) for unix sockets, or None if not known. | werkzeug.wrappers.index#werkzeug.wrappers.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. | werkzeug.wrappers.index#werkzeug.wrappers.Request.shallow |
user_agent_class
alias of werkzeug.useragents._UserAgent | werkzeug.wrappers.index#werkzeug.wrappers.Request.user_agent_class |
_get_file_stream(total_content_length, content_type, filename=None, content_length=None)
Called to get a stream for the file upload. This must provide a file-like class with read(), readline() and seek() methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. Parameters
total_content_length (Optional[int]) – the total content length of all the data in the request combined. This value is guaranteed to be there.
content_type (Optional[str]) – the mimetype of the uploaded file.
filename (Optional[str]) – the filename of the uploaded file. May be None.
content_length (Optional[int]) – the length of this file. This value is usually not provided because webbrowsers do not provide this value. Return type
BinaryIO | werkzeug.wrappers.index#werkzeug.wrappers.Request._get_file_stream |
class werkzeug.datastructures.RequestCacheControl(values=(), on_update=None)
A cache control for requests. This is immutable and gives access to all the request-relevant cache control headers. To get a header of the RequestCacheControl object again you can convert the object into a string or call the to_header() method. If you plan to subclass it and add your own items have a look at the sourcecode for that class. Changelog New in version 0.5: In previous versions a CacheControl class existed that was used both for request and response.
no_cache
accessor for ‘no-cache’
no_store
accessor for ‘no-store’
max_age
accessor for ‘max-age’
no_transform
accessor for ‘no-transform’
property max_stale
accessor for ‘max-stale’
property min_fresh
accessor for ‘min-fresh’
property only_if_cached
accessor for ‘only-if-cached’ | werkzeug.datastructures.index#werkzeug.datastructures.RequestCacheControl |
max_age
accessor for ‘max-age’ | werkzeug.datastructures.index#werkzeug.datastructures.RequestCacheControl.max_age |
no_cache
accessor for ‘no-cache’ | werkzeug.datastructures.index#werkzeug.datastructures.RequestCacheControl.no_cache |
no_store
accessor for ‘no-store’ | werkzeug.datastructures.index#werkzeug.datastructures.RequestCacheControl.no_store |
no_transform
accessor for ‘no-transform’ | werkzeug.datastructures.index#werkzeug.datastructures.RequestCacheControl.no_transform |
werkzeug.wsgi.responder(f)
Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example: @responder
def application(environ, start_response):
return Response('Hello World!')
Parameters
f (Callable[[...], WSGIApplication]) – Return type
WSGIApplication | werkzeug.wsgi.index#werkzeug.wsgi.responder |
class werkzeug.wrappers.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)
Represents an outgoing WSGI HTTP response with body, status, and headers. Has properties and methods for using the functionality defined by various HTTP specs. The response body is flexible to support different use cases. The simple form is passing bytes, or a string which will be encoded as UTF-8. Passing an iterable of bytes or strings makes this a streaming response. A generator is particularly useful for building a CSV file in memory or using SSE (Server Sent Events). A file-like object is also iterable, although the send_file() helper should be used in that case. The response object is itself a WSGI application callable. When called (__call__()) with environ and start_response, it will pass its status and headers to start_response then return its body as an iterable. from werkzeug.wrappers.response import Response
def index():
return Response("Hello, World!")
def application(environ, start_response):
path = environ.get("PATH_INFO") or "/"
if path == "/":
response = index()
else:
response = Response("Not Found", status=404)
return response(environ, start_response)
Parameters
response (Union[Iterable[str], Iterable[bytes]]) – The data for the body of the response. A string or bytes, or tuple or list of strings or bytes, for a fixed-length response, or any other iterable of strings or bytes for a streaming response. Defaults to an empty body.
status (Optional[Union[int, str, http.HTTPStatus]]) – The status code for the response. Either an int, in which case the default status message is added, or a string in the form {code} {message}, like 404 Not Found. Defaults to 200.
headers (werkzeug.datastructures.Headers) – A Headers object, or a list of (key, value) tuples that will be converted to a Headers object.
mimetype (Optional[str]) – The mime type (content type without charset or other parameters) of the response. If the value starts with text/ (or matches some other special cases), the charset will be added to create the content_type.
content_type (Optional[str]) – The full content type of the response. Overrides building the value from mimetype.
direct_passthrough (bool) – 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. Return type
None Changed in version 2.0: Combine BaseResponse and mixins into a single Response class. Using the old classes is deprecated and will be removed in Werkzeug 2.1. Changelog Changed in version 0.5: The direct_passthrough parameter was added.
__call__(environ, start_response)
Process this response as WSGI application. Parameters
environ (WSGIEnvironment) – the WSGI environment.
start_response (StartResponse) – the response callable provided by the WSGI server. Returns
an application iterator Return type
Iterable[bytes]
_ensure_sequence(mutable=False)
This method can be called by methods that need a sequence. If mutable is true, it will also ensure that the response sequence is a standard Python list. Changelog New in version 0.6. Parameters
mutable (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.
autocorrect_location_header = True
Should this response object correct the location header to be RFC conformant? This is true by default. Changelog New in version 0.8.
automatically_set_content_length = True
Should this response object automatically set the content-length header if possible? This is true by default. Changelog New in version 0.8.
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]]]
implicit_sequence_conversion = True
if set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list. Changelog New in version 0.6.2: That attribute was previously called implicit_seqence_conversion. (Notice the typo). If you did use this feature, you have to adapt your code to the name change.
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.
json_module = <module 'json' from '/home/docs/.pyenv/versions/3.7.9/lib/python3.7/json/__init__.py'>
A module or other object that has dumps and loads functions that match the API of the built-in json module.
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 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.
response: Union[Iterable[str], Iterable[bytes]]
The response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8. Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time.
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. | werkzeug.wrappers.index#werkzeug.wrappers.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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.accept_ranges |
access_control_allow_headers
Which headers can be sent with the cross origin request. | werkzeug.wrappers.index#werkzeug.wrappers.Response.access_control_allow_headers |
access_control_allow_methods
Which methods can be used for the cross origin request. | werkzeug.wrappers.index#werkzeug.wrappers.Response.access_control_allow_methods |
access_control_allow_origin
The origin or ‘*’ for any origin that may make cross origin requests. | werkzeug.wrappers.index#werkzeug.wrappers.Response.access_control_allow_origin |
access_control_expose_headers
Which headers can be shared by the browser to JavaScript code. | werkzeug.wrappers.index#werkzeug.wrappers.Response.access_control_expose_headers |
access_control_max_age
The maximum age in seconds the access control settings can be cached for. | werkzeug.wrappers.index#werkzeug.wrappers.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 | werkzeug.wrappers.index#werkzeug.wrappers.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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.age |
autocorrect_location_header = True
Should this response object correct the location header to be RFC conformant? This is true by default. Changelog New in version 0.8. | werkzeug.wrappers.index#werkzeug.wrappers.Response.autocorrect_location_header |
automatically_set_content_length = True
Should this response object automatically set the content-length header if possible? This is true by default. Changelog New in version 0.8. | werkzeug.wrappers.index#werkzeug.wrappers.Response.automatically_set_content_length |
calculate_content_length()
Returns the content length if available or None otherwise. Return type
Optional[int] | werkzeug.wrappers.index#werkzeug.wrappers.Response.calculate_content_length |
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] | werkzeug.wrappers.index#werkzeug.wrappers.Response.call_on_close |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.content_encoding |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.content_length |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.content_location |
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.) | werkzeug.wrappers.index#werkzeug.wrappers.Response.content_md5 |
content_security_policy
The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks. | werkzeug.wrappers.index#werkzeug.wrappers.Response.content_security_policy |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.content_security_policy_report_only |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.content_type |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.cross_origin_embedder_policy |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.cross_origin_opener_policy |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.date |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.delete_cookie |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.direct_passthrough |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.expires |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.force_type |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.freeze |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.from_app |
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] | werkzeug.wrappers.index#werkzeug.wrappers.Response.get_app_iter |
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] | werkzeug.wrappers.index#werkzeug.wrappers.Response.get_data |
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]] | werkzeug.wrappers.index#werkzeug.wrappers.Response.get_etag |
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] | werkzeug.wrappers.index#werkzeug.wrappers.Response.get_json |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.get_wsgi_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]]] | werkzeug.wrappers.index#werkzeug.wrappers.Response.get_wsgi_response |
implicit_sequence_conversion = True
if set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list. Changelog New in version 0.6.2: That attribute was previously called implicit_seqence_conversion. (Notice the typo). If you did use this feature, you have to adapt your code to the name change. | werkzeug.wrappers.index#werkzeug.wrappers.Response.implicit_sequence_conversion |
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] | werkzeug.wrappers.index#werkzeug.wrappers.Response.iter_encoded |
json_module = <module 'json' from '/home/docs/.pyenv/versions/3.7.9/lib/python3.7/json/__init__.py'>
A module or other object that has dumps and loads functions that match the API of the built-in json module. | werkzeug.wrappers.index#werkzeug.wrappers.Response.json_module |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.last_modified |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.location |
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. | werkzeug.wrappers.index#werkzeug.wrappers.Response.make_conditional |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.make_sequence |
response: Union[Iterable[str], Iterable[bytes]]
The response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8. Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time. | werkzeug.wrappers.index#werkzeug.wrappers.Response.response |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.set_cookie |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.set_data |
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 | werkzeug.wrappers.index#werkzeug.wrappers.Response.set_etag |
_ensure_sequence(mutable=False)
This method can be called by methods that need a sequence. If mutable is true, it will also ensure that the response sequence is a standard Python list. Changelog New in version 0.6. Parameters
mutable (bool) – Return type
None | werkzeug.wrappers.index#werkzeug.wrappers.Response._ensure_sequence |
__call__(environ, start_response)
Process this response as WSGI application. Parameters
environ (WSGIEnvironment) – the WSGI environment.
start_response (StartResponse) – the response callable provided by the WSGI server. Returns
an application iterator Return type
Iterable[bytes] | werkzeug.wrappers.index#werkzeug.wrappers.Response.__call__ |
class werkzeug.datastructures.ResponseCacheControl(values=(), on_update=None)
A cache control for responses. Unlike RequestCacheControl this is mutable and gives access to response-relevant cache control headers. To get a header of the ResponseCacheControl object again you can convert the object into a string or call the to_header() method. If you plan to subclass it and add your own items have a look at the sourcecode for that class. Changelog New in version 0.5: In previous versions a CacheControl class existed that was used both for request and response.
no_cache
accessor for ‘no-cache’
no_store
accessor for ‘no-store’
max_age
accessor for ‘max-age’
no_transform
accessor for ‘no-transform’
property immutable
accessor for ‘immutable’
property must_revalidate
accessor for ‘must-revalidate’
property private
accessor for ‘private’
property proxy_revalidate
accessor for ‘proxy-revalidate’
property public
accessor for ‘public’
property s_maxage
accessor for ‘s-maxage’ | werkzeug.datastructures.index#werkzeug.datastructures.ResponseCacheControl |
max_age
accessor for ‘max-age’ | werkzeug.datastructures.index#werkzeug.datastructures.ResponseCacheControl.max_age |
no_cache
accessor for ‘no-cache’ | werkzeug.datastructures.index#werkzeug.datastructures.ResponseCacheControl.no_cache |
no_store
accessor for ‘no-store’ | werkzeug.datastructures.index#werkzeug.datastructures.ResponseCacheControl.no_store |
no_transform
accessor for ‘no-transform’ | werkzeug.datastructures.index#werkzeug.datastructures.ResponseCacheControl.no_transform |
class werkzeug.routing.Rule(string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, merge_slashes=None, redirect_to=None, alias=False, host=None, websocket=False)
A Rule represents one URL pattern. There are some options for Rule that change the way it behaves and are passed to the Rule constructor. Note that besides the rule-string all arguments must be keyword arguments in order to not break the application on Werkzeug upgrades.
string
Rule strings basically are just normal URL paths with placeholders in the format <converter(arguments):name> where the converter and the arguments are optional. If no converter is defined the default converter is used which means string in the normal configuration. URL rules that end with a slash are branch URLs, others are leaves. If you have strict_slashes enabled (which is the default), all branch URLs that are matched without a trailing slash will trigger a redirect to the same URL with the missing slash appended. The converters are defined on the Map.
endpoint
The endpoint for this rule. This can be anything. A reference to a function, a string, a number etc. The preferred way is using a string because the endpoint is used for URL generation.
defaults
An optional dict with defaults for other rules with the same endpoint. This is a bit tricky but useful if you want to have unique URLs: url_map = Map([
Rule('/all/', defaults={'page': 1}, endpoint='all_entries'),
Rule('/all/page/<int:page>', endpoint='all_entries')
])
If a user now visits http://example.com/all/page/1 he will be redirected to http://example.com/all/. If redirect_defaults is disabled on the Map instance this will only affect the URL generation.
subdomain
The subdomain rule string for this rule. If not specified the rule only matches for the default_subdomain of the map. If the map is not bound to a subdomain this feature is disabled. Can be useful if you want to have user profiles on different subdomains and all subdomains are forwarded to your application: url_map = Map([
Rule('/', subdomain='<username>', endpoint='user/homepage'),
Rule('/stats', subdomain='<username>', endpoint='user/stats')
])
methods
A sequence of http methods this rule applies to. If not specified, all methods are allowed. For example this can be useful if you want different endpoints for POST and GET. If methods are defined and the path matches but the method matched against is not in this list or in the list of another rule for that path the error raised is of the type MethodNotAllowed rather than NotFound. If GET is present in the list of methods and HEAD is not, HEAD is added automatically.
strict_slashes
Override the Map setting for strict_slashes only for this rule. If not specified the Map setting is used.
merge_slashes
Override Map.merge_slashes for this rule.
build_only
Set this to True and the rule will never match but will create a URL that can be build. This is useful if you have resources on a subdomain or folder that are not handled by the WSGI application (like static data)
redirect_to
If given this must be either a string or callable. In case of a callable it’s called with the url adapter that triggered the match and the values of the URL as keyword arguments and has to return the target for the redirect, otherwise it has to be a string with placeholders in rule syntax: def foo_with_slug(adapter, id):
# ask the database for the slug for the old id. this of
# course has nothing to do with werkzeug.
return f'foo/{Foo.get_slug_for_id(id)}'
url_map = Map([
Rule('/foo/<slug>', endpoint='foo'),
Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'),
Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug)
])
When the rule is matched the routing system will raise a RequestRedirect exception with the target for the redirect. Keep in mind that the URL will be joined against the URL root of the script so don’t use a leading slash on the target URL unless you really mean root of that domain.
alias
If enabled this rule serves as an alias for another rule with the same endpoint and arguments.
host
If provided and the URL map has host matching enabled this can be used to provide a match rule for the whole host. This also means that the subdomain feature is disabled.
websocket
If True, this rule is only matches for WebSocket (ws://, wss://) requests. By default, rules will only match for HTTP requests. Changelog New in version 1.0: Added websocket. New in version 1.0: Added merge_slashes. New in version 0.7: Added alias and host. Changed in version 0.6.1: HEAD is added to methods if GET is present. Parameters
string (str) –
defaults (Optional[Mapping[str, Any]]) –
subdomain (Optional[str]) –
methods (Optional[Iterable[str]]) –
build_only (bool) –
endpoint (Optional[str]) –
strict_slashes (Optional[bool]) –
merge_slashes (Optional[bool]) –
redirect_to (Optional[Union[str, Callable[[...], str]]]) –
alias (bool) –
host (Optional[str]) –
websocket (bool) – Return type
None
empty()
Return an unbound copy of this rule. This can be useful if want to reuse an already bound URL for another map. See get_empty_kwargs to override what keyword arguments are provided to the new copy. Return type
werkzeug.routing.Rule | werkzeug.routing.index#werkzeug.routing.Rule |
empty()
Return an unbound copy of this rule. This can be useful if want to reuse an already bound URL for another map. See get_empty_kwargs to override what keyword arguments are provided to the new copy. Return type
werkzeug.routing.Rule | werkzeug.routing.index#werkzeug.routing.Rule.empty |
class werkzeug.routing.RuleFactory
As soon as you have more complex URL setups it’s a good idea to use rule factories to avoid repetitive tasks. Some of them are builtin, others can be added by subclassing RuleFactory and overriding get_rules.
get_rules(map)
Subclasses of RuleFactory have to override this method and return an iterable of rules. Parameters
map (werkzeug.routing.Map) – Return type
Iterable[werkzeug.routing.Rule] | werkzeug.routing.index#werkzeug.routing.RuleFactory |
get_rules(map)
Subclasses of RuleFactory have to override this method and return an iterable of rules. Parameters
map (werkzeug.routing.Map) – Return type
Iterable[werkzeug.routing.Rule] | werkzeug.routing.index#werkzeug.routing.RuleFactory.get_rules |
class werkzeug.routing.RuleTemplate(rules)
Returns copies of the rules wrapped and expands string templates in the endpoint, rule, defaults or subdomain sections. Here a small example for such a rule template: from werkzeug.routing import Map, Rule, RuleTemplate
resource = RuleTemplate([
Rule('/$name/', endpoint='$name.list'),
Rule('/$name/<int:id>', endpoint='$name.show')
])
url_map = Map([resource(name='user'), resource(name='page')])
When a rule template is called the keyword arguments are used to replace the placeholders in all the string parameters. Parameters
rules (Iterable[Rule]) – Return type
None | werkzeug.routing.index#werkzeug.routing.RuleTemplate |
werkzeug.serving.run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, exclude_patterns=None, reloader_interval=1, reloader_type='auto', threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None)
Start a WSGI application. Optional features include a reloader, multithreading and fork support. This function has a command-line interface too: python -m werkzeug.serving --help
Changed in version 2.0: Added exclude_patterns parameter. Changelog Changed in version 0.15: Bind to a Unix socket by passing a path that starts with unix:// as the hostname. New in version 0.10: Improved the reloader and added support for changing the backend through the reloader_type parameter. See Reloader for more information. New in version 0.9: Added command-line interface. New in version 0.8: Added support for automatically loading a SSL context from certificate file and private key. New in version 0.6: support for SSL was added. New in version 0.5: static_files was added to simplify serving of static files as well as passthrough_errors. Parameters
hostname (str) – The host to bind to, for example 'localhost'. If the value is a path that starts with unix:// it will bind to a Unix socket instead of a TCP socket..
port (int) – The port for the server. eg: 8080
application (WSGIApplication) – the WSGI application to execute
use_reloader (bool) – should the server automatically restart the python process if modules were changed?
use_debugger (bool) – should the werkzeug debugging system be used?
use_evalex (bool) – should the exception evaluation feature be enabled?
extra_files (Optional[Iterable[str]]) – a list of files the reloader should watch additionally to the modules. For example configuration files.
exclude_patterns (Optional[Iterable[str]]) – List of fnmatch patterns to ignore when running the reloader. For example, ignore cache files that shouldn’t reload when updated.
reloader_interval (int) – the interval for the reloader in seconds.
reloader_type (str) – the type of reloader to use. The default is auto detection. Valid values are 'stat' and 'watchdog'. See Reloader for more information.
threaded (bool) – should the process handle each request in a separate thread?
processes (int) – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.
request_handler (Optional[Type[werkzeug.serving.WSGIRequestHandler]]) – optional parameter that can be used to replace the default one. You can use this to replace it with a different BaseHTTPRequestHandler subclass.
static_files (Optional[Dict[str, Union[str, Tuple[str, str]]]]) – a list or dict of paths for static files. This works exactly like SharedDataMiddleware, it’s actually just wrapping the application in that middleware before serving.
passthrough_errors (bool) – set this to True to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.)
ssl_context (Optional[Union[ssl.SSLContext, Tuple[str, Optional[str]], te.Literal['adhoc']]]) – an SSL context for the connection. Either an ssl.SSLContext, a tuple in the form (cert_file, pkey_file), the string 'adhoc' if the server should automatically create one, or None to disable SSL (which is the default). Return type
None | werkzeug.serving.index#werkzeug.serving.run_simple |
werkzeug.test.run_wsgi_app(app, environ, buffered=False)
Return a tuple in the form (app_iter, status, headers) of the application output. This works best if you pass it an application that returns an iterator 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. If passed an invalid WSGI application the behavior of this function is undefined. Never pass non-conforming WSGI applications to this function. Parameters
app (WSGIApplication) – the application to execute.
buffered (bool) – set to True to enforce buffering.
environ (WSGIEnvironment) – Returns
tuple in the form (app_iter, status, headers) Return type
Tuple[Iterable[bytes], str, werkzeug.datastructures.Headers] | werkzeug.test.index#werkzeug.test.run_wsgi_app |
werkzeug.security.safe_join(directory, *pathnames)
Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. Parameters
directory (str) – The trusted base directory.
pathnames (str) – The untrusted path components relative to the base directory. Returns
A safe path, otherwise None. Return type
Optional[str] | werkzeug.utils.index#werkzeug.security.safe_join |
werkzeug.security.safe_str_cmp(a, b)
This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns True if the two strings are equal, or False if they are not. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hmac.compare_digest() instead. Changelog New in version 0.7. Parameters
a (str) –
b (str) – Return type
bool | werkzeug.utils.index#werkzeug.security.safe_str_cmp |
werkzeug.utils.secure_filename(filename)
Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to os.path.join(). The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov")
'My_cool_movie.mov'
>>> secure_filename("../../../etc/passwd")
'etc_passwd'
>>> secure_filename('i contain cool \xfcml\xe4uts.txt')
'i_contain_cool_umlauts.txt'
The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one. Changelog New in version 0.5. Parameters
filename (str) – the filename to secure Return type
str | werkzeug.utils.index#werkzeug.utils.secure_filename |
werkzeug.utils.send_file(path_or_file, environ, mimetype=None, as_attachment=False, download_name=None, conditional=True, etag=True, last_modified=None, max_age=None, use_x_sendfile=False, response_class=None, _root_path=None)
Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with io.BytesIO. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn’t intend. If the WSGI server sets a file_wrapper in environ, it is used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, if the HTTP server supports X-Sendfile, use_x_sendfile=True will tell the server to send the given path, which is much more efficient than reading it in Python. Parameters
path_or_file (Union[os.PathLike, str, BinaryIO]) – The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data.
environ (WSGIEnvironment) – The WSGI environ for the current request.
mimetype (Optional[str]) – The MIME type to send for the file. If not provided, it will try to detect it from the file name.
as_attachment (bool) – Indicate to a browser that it should offer to save the file instead of displaying it.
download_name (Optional[str]) – The default name browsers will use when saving the file. Defaults to the passed file name.
conditional (bool) – Enable conditional and range responses based on request headers. Requires passing a file path and environ.
etag (Union[bool, str]) – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead.
last_modified (Optional[Union[datetime.datetime, int, float]]) – The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path.
max_age (Optional[Union[int, Callable[[Optional[Union[os.PathLike, str]]], int]]]) – How long the client should cache the file, in seconds. If set, Cache-Control will be public, otherwise it will be no-cache to prefer conditional caching.
use_x_sendfile (bool) – Set the X-Sendfile header to let the server to efficiently send the file. Requires support from the HTTP server. Requires passing a file path.
response_class (Optional[Type[Response]]) – Build the response using this class. Defaults to Response.
_root_path (Optional[Union[os.PathLike, str]]) – Do not use. For internal use only. Use send_from_directory() to safely send files under a path. Return type
Response New in version 2.0: Adapted from Flask’s implementation. Changed in version 2.0: download_name replaces Flask’s attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead. Changed in version 2.0: max_age replaces Flask’s cache_timeout parameter. conditional is enabled and max_age is not set by default. Changed in version 2.0: etag replaces Flask’s add_etags parameter. It can be a string to use instead of generating one. Changed in version 2.0: If an encoding is returned when guessing mimetype from download_name, set the Content-Encoding header. | werkzeug.utils.index#werkzeug.utils.send_file |
class werkzeug.middleware.shared_data.SharedDataMiddleware(app, exports, disallow=None, cache=True, cache_timeout=43200, fallback_mimetype='application/octet-stream')
A WSGI middleware which provides static content for development environments or simple server setups. Its usage is quite simple: import os
from werkzeug.middleware.shared_data import SharedDataMiddleware
app = SharedDataMiddleware(app, {
'/shared': os.path.join(os.path.dirname(__file__), 'shared')
})
The contents of the folder ./shared will now be available on http://example.com/shared/. This is pretty useful during development because a standalone media server is not required. Files can also be mounted on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders. If pkg_resources is available you can also tell the middleware to serve files from package data: app = SharedDataMiddleware(app, {
'/static': ('myapplication', 'static')
})
This will then serve the static folder in the myapplication Python package. The optional disallow parameter can be a list of fnmatch() rules for files that are not accessible from the web. If cache is set to False no caching headers are sent. Currently the middleware does not support non-ASCII filenames. If the encoding on the file system happens to match the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files. The middleware will guess the mimetype using the Python mimetype module. If it’s unable to figure out the charset it will fall back to fallback_mimetype. Parameters
app (WSGIApplication) – the application to wrap. If you don’t want to wrap an application you can pass it NotFound.
exports (Union[Dict[str, Union[str, Tuple[str, str]]], Iterable[Tuple[str, Union[str, Tuple[str, str]]]]]) – a list or dict of exported files and folders.
disallow (None) – a list of fnmatch() rules.
cache (bool) – enable or disable caching headers.
cache_timeout (int) – the cache timeout in seconds for the headers.
fallback_mimetype (str) – The fallback mimetype for unknown files. Return type
None Changelog Changed in version 1.0: The default fallback_mimetype is application/octet-stream. If a filename looks like a text mimetype, the utf-8 charset is added to it. New in version 0.6: Added fallback_mimetype. Changed in version 0.5: Added cache_timeout.
is_allowed(filename)
Subclasses can override this method to disallow the access to certain files. However by providing disallow in the constructor this method is overwritten. Parameters
filename (str) – Return type
bool | werkzeug.middleware.shared_data.index#werkzeug.middleware.shared_data.SharedDataMiddleware |
is_allowed(filename)
Subclasses can override this method to disallow the access to certain files. However by providing disallow in the constructor this method is overwritten. Parameters
filename (str) – Return type
bool | werkzeug.middleware.shared_data.index#werkzeug.middleware.shared_data.SharedDataMiddleware.is_allowed |
class werkzeug.routing.Subdomain(subdomain, rules)
All URLs provided by this factory have the subdomain set to a specific domain. For example if you want to use the subdomain for the current language this can be a good setup: url_map = Map([
Rule('/', endpoint='#select_language'),
Subdomain('<string(length=2):lang_code>', [
Rule('/', endpoint='index'),
Rule('/about', endpoint='about'),
Rule('/help', endpoint='help')
])
])
All the rules except for the '#select_language' endpoint will now listen on a two letter long subdomain that holds the language code for the current request. Parameters
subdomain (str) –
rules (Iterable[Rule]) – Return type
None | werkzeug.routing.index#werkzeug.routing.Subdomain |
class werkzeug.routing.Submount(path, rules)
Like Subdomain but prefixes the URL rule with a given string: url_map = Map([
Rule('/', endpoint='index'),
Submount('/blog', [
Rule('/', endpoint='blog/index'),
Rule('/entry/<entry_slug>', endpoint='blog/show')
])
])
Now the rule 'blog/show' matches /blog/entry/<entry_slug>. Parameters
path (str) –
rules (Iterable[Rule]) – Return type
None | werkzeug.routing.index#werkzeug.routing.Submount |
class werkzeug.test.TestResponse(response, status, headers, request, history=(), **kwargs)
Response subclass that provides extra information about requests made with the test Client. Test client requests will always return an instance of this class. If a custom response class is passed to the client, it is subclassed along with this to support test information. If the test request included large files, or if the application is serving a file, call close() to close any open files and prevent Python showing a ResourceWarning. Parameters
response (Union[Iterable[str], Iterable[bytes]]) –
status (str) –
headers (werkzeug.datastructures.Headers) –
request (werkzeug.wrappers.request.Request) –
history (Tuple[werkzeug.test.TestResponse, ...]) –
kwargs (Any) – Return type
None
request: werkzeug.wrappers.request.Request
A request object with the environ used to make the request that resulted in this response.
history: Tuple[werkzeug.test.TestResponse, ...]
A list of intermediate responses. Populated when the test request is made with follow_redirects enabled. | werkzeug.test.index#werkzeug.test.TestResponse |
history: Tuple[werkzeug.test.TestResponse, ...]
A list of intermediate responses. Populated when the test request is made with follow_redirects enabled. | werkzeug.test.index#werkzeug.test.TestResponse.history |
request: werkzeug.wrappers.request.Request
A request object with the environ used to make the request that resulted in this response. | werkzeug.test.index#werkzeug.test.TestResponse.request |
werkzeug.testapp.test_app(environ, start_response)
Simple test application that dumps the environment. You can use it to check if Werkzeug is working properly: >>> from werkzeug.serving import run_simple
>>> from werkzeug.testapp import test_app
>>> run_simple('localhost', 3000, test_app)
* Running on http://localhost:3000/
The application displays important information from the WSGI environment, the Python interpreter and the installed libraries. Parameters
environ (WSGIEnvironment) –
start_response (StartResponse) – Return type
Iterable[bytes] | werkzeug.wsgi.index#werkzeug.testapp.test_app |
class werkzeug.datastructures.TypeConversionDict
Works like a regular dict but the get() method can perform type conversions. MultiDict and CombinedMultiDict are subclasses of this class and provide the same feature. Changelog New in version 0.5.
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found: >>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
Parameters
key – The key to be looked up.
default – The default value to be returned if the key can’t be looked up. If not further specified None is returned.
type – A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the default value is returned. | werkzeug.datastructures.index#werkzeug.datastructures.TypeConversionDict |
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found: >>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
Parameters
key – The key to be looked up.
default – The default value to be returned if the key can’t be looked up. If not further specified None is returned.
type – A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the default value is returned. | werkzeug.datastructures.index#werkzeug.datastructures.TypeConversionDict.get |
werkzeug.utils.unescape(s)
The reverse of escape(). This unescapes all the HTML entities, not only those inserted by escape. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead. Parameters
s (str) – Return type
str | werkzeug.utils.index#werkzeug.utils.unescape |
Unicode Werkzeug uses strings internally everwhere text data is assumed, even if the HTTP standard is not Unicode aware. Basically all incoming data is decoded from the charset (UTF-8 by default) so that you don’t work with bytes directly. Outgoing data is encoded into the target charset. Unicode in Python Imagine you have the German Umlaut ö. In ASCII you cannot represent that character, but in the latin-1 and utf-8 character sets you can represent it, but they look different when encoded: >>> "ö".encode("latin1")
b'\xf6'
>>> "ö".encode("utf-8")
b'\xc3\xb6'
An ö looks different depending on the encoding which makes it hard to work with it as bytes. Instead, Python treats strings as Unicode text and stores the information LATIN SMALL LETTER O WITH DIAERESIS instead of the bytes for ö in a specific encoding. The length of a string with 1 character will be 1, where the length of the bytes might be some other value. Unicode in HTTP However, the HTTP spec was written in a time where ASCII bytes were the common way data was represented. To work around this for the modern web, Werkzeug decodes and encodes incoming and outgoing data automatically. Data sent from the browser to the web application is decoded from UTF-8 bytes into a string. Data sent from the application back to the browser is encoded back to UTF-8. Error Handling Functions that do internal encoding or decoding accept an errors keyword argument that is passed to str.decode() and str.encode(). The default is 'replace' so that errors are easy to spot. It might be useful to set it to 'strict' in order to catch the error and report the bad data to the client. Request and Response Objects In most cases, you should stick with Werkzeug’s default encoding of UTF-8. If you have a specific reason to, you can subclass wrappers.Request and wrappers.Response to change the encoding and error handling. from werkzeug.wrappers.request import Request
from werkzeug.wrappers.response import Response
class Latin1Request(Request):
charset = "latin1"
encoding_errors = "strict"
class Latin1Response(Response):
charset = "latin1"
The error handling can only be changed for the request. Werkzeug will always raise errors when encoding to bytes in the response. It’s your responsibility to not create data that is not present in the target charset. This is not an issue for UTF-8. | werkzeug.unicode.index |
class werkzeug.routing.UnicodeConverter(map, minlength=1, maxlength=None, length=None)
This converter is the default converter and accepts any string but only one path segment. Thus the string can not include a slash. This is the default validator. Example: Rule('/pages/<page>'),
Rule('/<string(length=2):lang_code>')
Parameters
map (Map) – the Map.
minlength (int) – the minimum length of the string. Must be greater or equal 1.
maxlength (Optional[int]) – the maximum length of the string.
length (Optional[int]) – the exact length of the string. Return type
None | werkzeug.routing.index#werkzeug.routing.UnicodeConverter |
werkzeug.http.unquote_etag(etag)
Unquote a single etag: >>> unquote_etag('W/"bar"')
('bar', True)
>>> unquote_etag('"bar"')
('bar', False)
Parameters
etag (Optional[str]) – the etag identifier to unquote. Returns
a (etag, weak) tuple. Return type
Union[Tuple[str, bool], Tuple[None, None]] | werkzeug.http.index#werkzeug.http.unquote_etag |
werkzeug.http.unquote_header_value(value, is_filename=False)
Unquotes a header value. (Reversal of quote_header_value()). This does not use the real unquoting but what browsers are actually using for quoting. Changelog New in version 0.5. Parameters
value (str) – the header value to unquote.
is_filename (bool) – The value represents a filename or path. Return type
str | werkzeug.http.index#werkzeug.http.unquote_header_value |
werkzeug.urls.uri_to_iri(uri, charset='utf-8', errors='werkzeug.url_quote')
Convert a URI to an IRI. All valid UTF-8 characters are unquoted, leaving all reserved and invalid characters quoted. If the URL has a domain, it is decoded from Punycode. >>> uri_to_iri("http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF")
'http://\u2603.net/p\xe5th?q=\xe8ry%DF'
Parameters
uri (Union[str, Tuple[str, str, str, str, str]]) – The URI to convert.
charset (str) – The encoding to encode unquoted bytes with.
errors (str) – Error handler to use during bytes.encode. By default, invalid bytes are left quoted. Return type
str Changelog Changed in version 0.15: All reserved and invalid characters remain quoted. Previously, only some reserved characters were preserved, and invalid bytes were replaced instead of left quoted. New in version 0.6. | werkzeug.urls.index#werkzeug.urls.uri_to_iri |
class werkzeug.urls.URL(scheme, netloc, path, query, fragment)
Represents a parsed URL. This behaves like a regular tuple but also has some extra attributes that give further insight into the URL. Create new instance of _URLTuple(scheme, netloc, path, query, fragment) Parameters
scheme (str) –
netloc (str) –
path (str) –
query (str) –
fragment (str) –
encode(charset='utf-8', errors='replace')
Encodes the URL to a tuple made out of bytes. The charset is only being used for the path, query and fragment. Parameters
charset (str) –
errors (str) – Return type
werkzeug.urls.BytesURL | werkzeug.urls.index#werkzeug.urls.URL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.