doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
torch.vstack(tensors, *, out=None) β†’ Tensor Stack tensors in sequence vertically (row wise). This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by torch.atleast_2d(). Parameters tensors (sequence of Tensors) – sequence of tensors to concatenate Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a = torch.tensor([1, 2, 3]) >>> b = torch.tensor([4, 5, 6]) >>> torch.vstack((a,b)) tensor([[1, 2, 3], [4, 5, 6]]) >>> a = torch.tensor([[1],[2],[3]]) >>> b = torch.tensor([[4],[5],[6]]) >>> torch.vstack((a,b)) tensor([[1], [2], [3], [4], [5], [6]])
torch.generated.torch.vstack#torch.vstack
torch.where(condition, x, y) β†’ Tensor Return a tensor of elements selected from either x or y, depending on condition. The operation is defined as: outi={xiif conditioniyiotherwise\text{out}_i = \begin{cases} \text{x}_i & \text{if } \text{condition}_i \\ \text{y}_i & \text{otherwise} \\ \end{cases} Note The tensors condition, x, y must be broadcastable. Note Currently valid scalar and tensor combination are 1. Scalar of floating dtype and torch.double 2. Scalar of integral dtype and torch.long 3. Scalar of complex dtype and torch.complex128 Parameters condition (BoolTensor) – When True (nonzero), yield x, otherwise yield y x (Tensor or Scalar) – value (if :attr:x is a scalar) or values selected at indices where condition is True y (Tensor or Scalar) – value (if :attr:x is a scalar) or values selected at indices where condition is False Returns A tensor of shape equal to the broadcasted shape of condition, x, y Return type Tensor Example: >>> x = torch.randn(3, 2) >>> y = torch.ones(3, 2) >>> x tensor([[-0.4620, 0.3139], [ 0.3898, -0.7197], [ 0.0478, -0.1657]]) >>> torch.where(x > 0, x, y) tensor([[ 1.0000, 0.3139], [ 0.3898, 1.0000], [ 0.0478, 1.0000]]) >>> x = torch.randn(2, 2, dtype=torch.double) >>> x tensor([[ 1.0779, 0.0383], [-0.8785, -1.1089]], dtype=torch.float64) >>> torch.where(x > 0, x, 0.) tensor([[1.0779, 0.0383], [0.0000, 0.0000]], dtype=torch.float64) torch.where(condition) β†’ tuple of LongTensor torch.where(condition) is identical to torch.nonzero(condition, as_tuple=True). Note See also torch.nonzero().
torch.generated.torch.where#torch.where
torch.xlogy(input, other, *, out=None) β†’ Tensor Computes input * log(other) with the following cases. outi={NaNif otheri=NaN0if inputi=0.0inputiβˆ—log⁑(otheri)otherwise\text{out}_{i} = \begin{cases} \text{NaN} & \text{if } \text{other}_{i} = \text{NaN} \\ 0 & \text{if } \text{input}_{i} = 0.0 \\ \text{input}_{i} * \log{(\text{other}_{i})} & \text{otherwise} \end{cases} Similar to SciPy’s scipy.special.xlogy. Parameters input (Number or Tensor) – other (Number or Tensor) – Note At least one of input or other must be a tensor. Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> x = torch.zeros(5,) >>> y = torch.tensor([-1, 0, 1, float('inf'), float('nan')]) >>> torch.xlogy(x, y) tensor([0., 0., 0., 0., nan]) >>> x = torch.tensor([1, 2, 3]) >>> y = torch.tensor([3, 2, 1]) >>> torch.xlogy(x, y) tensor([1.0986, 1.3863, 0.0000]) >>> torch.xlogy(x, 4) tensor([1.3863, 2.7726, 4.1589]) >>> torch.xlogy(2, y) tensor([2.1972, 1.3863, 0.0000])
torch.generated.torch.xlogy#torch.xlogy
torch.zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) β†’ Tensor Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size. Parameters size (int...) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple. Keyword Arguments out (Tensor, optional) – the output tensor. dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()). layout (torch.layout, optional) – the desired layout of returned Tensor. Default: torch.strided. device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False. Example: >>> torch.zeros(2, 3) tensor([[ 0., 0., 0.], [ 0., 0., 0.]]) >>> torch.zeros(5) tensor([ 0., 0., 0., 0., 0.])
torch.generated.torch.zeros#torch.zeros
torch.zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) β†’ Tensor Returns a tensor filled with the scalar value 0, with the same size as input. torch.zeros_like(input) is equivalent to torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device). Warning As of 0.4, this function does not support an out keyword. As an alternative, the old torch.zeros_like(input, out=output) is equivalent to torch.zeros(input.size(), out=output). Parameters input (Tensor) – the size of input will determine size of the output tensor. Keyword Arguments dtype (torch.dtype, optional) – the desired data type of returned Tensor. Default: if None, defaults to the dtype of input. layout (torch.layout, optional) – the desired layout of returned tensor. Default: if None, defaults to the layout of input. device (torch.device, optional) – the desired device of returned tensor. Default: if None, defaults to the device of input. requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False. memory_format (torch.memory_format, optional) – the desired memory format of returned Tensor. Default: torch.preserve_format. Example: >>> input = torch.empty(2, 3) >>> torch.zeros_like(input) tensor([[ 0., 0., 0.], [ 0., 0., 0.]])
torch.generated.torch.zeros_like#torch.zeros_like
torch._assert(condition, message) [source] A wrapper around Python’s assert which is symbolically traceable.
torch.generated.torch._assert#torch._assert
werkzeug.exceptions.abort(status, *args, **kwargs) Raises an HTTPException for the given status code or WSGI application. If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that: abort(404) # 404 Not Found abort(Response('Hello World')) Parameters status (Union[int, Response]) – args (Any) – kwargs (Any) – Return type NoReturn
werkzeug.exceptions.index#werkzeug.exceptions.abort
class werkzeug.exceptions.Aborter(mapping=None, extra=None) When passed a dict of code -> exception items it can be used as callable that raises exceptions. If the first argument to the callable is an integer it will be looked up in the mapping, if it’s a WSGI application it will be raised in a proxy exception. The rest of the arguments are forwarded to the exception constructor. Parameters mapping (Optional[Dict[int, Type[werkzeug.exceptions.HTTPException]]]) – extra (Optional[Dict[int, Type[werkzeug.exceptions.HTTPException]]]) – Return type None
werkzeug.exceptions.index#werkzeug.exceptions.Aborter
class werkzeug.datastructures.Accept(values=()) An Accept object is just a list subclass for lists of (value, quality) tuples. It is automatically sorted by specificity and quality. All Accept objects work similar to a list but provide extra functionality for working with the data. Containment checks are normalized to the rules of that header: >>> a = CharsetAccept([('ISO-8859-1', 1), ('utf-8', 0.7)]) >>> a.best 'ISO-8859-1' >>> 'iso-8859-1' in a True >>> 'UTF8' in a True >>> 'utf7' in a False To get the quality for an item you can use normal item lookup: >>> print a['utf-8'] 0.7 >>> a['utf7'] 0 Changelog Changed in version 1.0.0: Accept internal values are no longer ordered alphabetically for equal quality tags. Instead the initial order is preserved. Changed in version 0.5: Accept objects are forced immutable now. property best The best match as value. best_match(matches, default=None) Returns the best match from a list of possible matches based on the specificity and quality of the client. If two items have the same quality and specificity, the one is returned that comes first. Parameters matches – a list of matches to check for default – the value that is returned if none match find(key) Get the position of an entry or return -1. Parameters key – The key to be looked up. index(key) Get the position of an entry or raise ValueError. Parameters key – The key to be looked up. Changelog Changed in version 0.5: This used to raise IndexError, which was inconsistent with the list API. quality(key) Returns the quality of the key. Changelog New in version 0.6: In previous versions you had to use the item-lookup syntax (eg: obj[key] instead of obj.quality(key)) to_header() Convert the header set into an HTTP header string. values() Iterate over all values.
werkzeug.datastructures.index#werkzeug.datastructures.Accept
best_match(matches, default=None) Returns the best match from a list of possible matches based on the specificity and quality of the client. If two items have the same quality and specificity, the one is returned that comes first. Parameters matches – a list of matches to check for default – the value that is returned if none match
werkzeug.datastructures.index#werkzeug.datastructures.Accept.best_match
find(key) Get the position of an entry or return -1. Parameters key – The key to be looked up.
werkzeug.datastructures.index#werkzeug.datastructures.Accept.find
index(key) Get the position of an entry or raise ValueError. Parameters key – The key to be looked up. Changelog Changed in version 0.5: This used to raise IndexError, which was inconsistent with the list API.
werkzeug.datastructures.index#werkzeug.datastructures.Accept.index
quality(key) Returns the quality of the key. Changelog New in version 0.6: In previous versions you had to use the item-lookup syntax (eg: obj[key] instead of obj.quality(key))
werkzeug.datastructures.index#werkzeug.datastructures.Accept.quality
to_header() Convert the header set into an HTTP header string.
werkzeug.datastructures.index#werkzeug.datastructures.Accept.to_header
values() Iterate over all values.
werkzeug.datastructures.index#werkzeug.datastructures.Accept.values
class werkzeug.routing.AnyConverter(map, *items) Matches one of the items provided. Items can either be Python identifiers or strings: Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>') Parameters map (Map) – the Map. items (str) – this function accepts the possible items as positional arguments. Return type None
werkzeug.routing.index#werkzeug.routing.AnyConverter
werkzeug.utils.append_slash_redirect(environ, code=301) Redirects to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already. Parameters environ (WSGIEnvironment) – the WSGI environment for the request that triggers the redirect. code (int) – the status code for the redirect. Return type Response
werkzeug.utils.index#werkzeug.utils.append_slash_redirect
class werkzeug.datastructures.Authorization(auth_type, data=None) Represents an Authorization header sent by the client. This is returned by parse_authorization_header(). It can be useful to create the object manually to pass to the test Client. Changelog Changed in version 0.5: This object became immutable. property cnonce If the server sent a qop-header in the WWW-Authenticate header, the client has to provide this value for HTTP digest auth. See the RFC for more details. property nc The nonce count value transmitted by clients if a qop-header is also transmitted. HTTP digest auth only. property nonce The nonce the server sent for digest auth, sent back by the client. A nonce should be unique for every 401 response for HTTP digest auth. property opaque The opaque header from the server returned unchanged by the client. It is recommended that this string be base64 or hexadecimal data. Digest auth only. property password When the authentication type is basic this is the password transmitted by the client, else None. property qop Indicates what β€œquality of protection” the client has applied to the message for HTTP digest auth. Note that this is a single token, not a quoted list of alternatives as in WWW-Authenticate. property realm This is the server realm sent back for HTTP digest auth. property response A string of 32 hex digits computed as defined in RFC 2617, which proves that the user knows a password. Digest auth only. to_header() Convert to a string value for an Authorization header. New in version 2.0: Added to support passing authorization to the test client. property uri The URI from Request-URI of the Request-Line; duplicated because proxies are allowed to change the Request-Line in transit. HTTP digest auth only. property username The username transmitted. This is set for both basic and digest auth all the time.
werkzeug.datastructures.index#werkzeug.datastructures.Authorization
to_header() Convert to a string value for an Authorization header. New in version 2.0: Added to support passing authorization to the test client.
werkzeug.datastructures.index#werkzeug.datastructures.Authorization.to_header
class werkzeug.urls.BaseURL(scheme, netloc, path, query, fragment) Superclass of URL and BytesURL. Create new instance of _URLTuple(scheme, netloc, path, query, fragment) Parameters scheme (str) – netloc (str) – path (str) – query (str) – fragment (str) – property ascii_host: Optional[str] Works exactly like host but will return a result that is restricted to ASCII. If it finds a netloc that is not ASCII it will attempt to idna decode it. This is useful for socket operations when the URL might include internationalized characters. property auth: Optional[str] The authentication part in the URL if available, None otherwise. decode_netloc() Decodes the netloc part into a string. Return type str decode_query(*args, **kwargs) Decodes the query part of the URL. Ths is a shortcut for calling url_decode() on the query argument. The arguments and keyword arguments are forwarded to url_decode() unchanged. Parameters args (Any) – kwargs (Any) – Return type ds.MultiDict[str, str] encode_netloc() Encodes the netloc part to an ASCII safe URL as bytes. Return type str get_file_location(pathformat=None) Returns a tuple with the location of the file in the form (server, location). If the netloc is empty in the URL or points to localhost, it’s represented as None. The pathformat by default is autodetection but needs to be set when working with URLs of a specific system. The supported values are 'windows' when working with Windows or DOS paths and 'posix' when working with posix paths. If the URL does not point to a local file, the server and location are both represented as None. Parameters pathformat (Optional[str]) – The expected format of the path component. Currently 'windows' and 'posix' are supported. Defaults to None which is autodetect. Return type Tuple[Optional[str], Optional[str]] property host: Optional[str] The host part of the URL if available, otherwise None. The host is either the hostname or the IP address mentioned in the URL. It will not contain the port. join(*args, **kwargs) Joins this URL with another one. This is just a convenience function for calling into url_join() and then parsing the return value again. Parameters args (Any) – kwargs (Any) – Return type werkzeug.urls.BaseURL property password: Optional[str] The password if it was part of the URL, None otherwise. This undergoes URL decoding and will always be a string. property port: Optional[int] The port in the URL as an integer if it was present, None otherwise. This does not fill in default ports. property raw_password: Optional[str] The password if it was part of the URL, None otherwise. Unlike password this one is not being decoded. property raw_username: Optional[str] The username if it was part of the URL, None otherwise. Unlike username this one is not being decoded. replace(**kwargs) Return an URL with the same values, except for those parameters given new values by whichever keyword arguments are specified. Parameters kwargs (Any) – Return type werkzeug.urls.BaseURL to_iri_tuple() Returns a URL tuple that holds a IRI. This will try to decode as much information as possible in the URL without losing information similar to how a web browser does it for the URL bar. It’s usually more interesting to directly call uri_to_iri() which will return a string. Return type werkzeug.urls.BaseURL to_uri_tuple() Returns a BytesURL tuple that holds a URI. This will encode all the information in the URL properly to ASCII using the rules a web browser would follow. It’s usually more interesting to directly call iri_to_uri() which will return a string. Return type werkzeug.urls.BaseURL to_url() Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling url_unparse() for this URL. Return type str property username: Optional[str] The username if it was part of the URL, None otherwise. This undergoes URL decoding and will always be a string.
werkzeug.urls.index#werkzeug.urls.BaseURL
decode_netloc() Decodes the netloc part into a string. Return type str
werkzeug.urls.index#werkzeug.urls.BaseURL.decode_netloc
decode_query(*args, **kwargs) Decodes the query part of the URL. Ths is a shortcut for calling url_decode() on the query argument. The arguments and keyword arguments are forwarded to url_decode() unchanged. Parameters args (Any) – kwargs (Any) – Return type ds.MultiDict[str, str]
werkzeug.urls.index#werkzeug.urls.BaseURL.decode_query
encode_netloc() Encodes the netloc part to an ASCII safe URL as bytes. Return type str
werkzeug.urls.index#werkzeug.urls.BaseURL.encode_netloc
get_file_location(pathformat=None) Returns a tuple with the location of the file in the form (server, location). If the netloc is empty in the URL or points to localhost, it’s represented as None. The pathformat by default is autodetection but needs to be set when working with URLs of a specific system. The supported values are 'windows' when working with Windows or DOS paths and 'posix' when working with posix paths. If the URL does not point to a local file, the server and location are both represented as None. Parameters pathformat (Optional[str]) – The expected format of the path component. Currently 'windows' and 'posix' are supported. Defaults to None which is autodetect. Return type Tuple[Optional[str], Optional[str]]
werkzeug.urls.index#werkzeug.urls.BaseURL.get_file_location
join(*args, **kwargs) Joins this URL with another one. This is just a convenience function for calling into url_join() and then parsing the return value again. Parameters args (Any) – kwargs (Any) – Return type werkzeug.urls.BaseURL
werkzeug.urls.index#werkzeug.urls.BaseURL.join
replace(**kwargs) Return an URL with the same values, except for those parameters given new values by whichever keyword arguments are specified. Parameters kwargs (Any) – Return type werkzeug.urls.BaseURL
werkzeug.urls.index#werkzeug.urls.BaseURL.replace
to_iri_tuple() Returns a URL tuple that holds a IRI. This will try to decode as much information as possible in the URL without losing information similar to how a web browser does it for the URL bar. It’s usually more interesting to directly call uri_to_iri() which will return a string. Return type werkzeug.urls.BaseURL
werkzeug.urls.index#werkzeug.urls.BaseURL.to_iri_tuple
to_uri_tuple() Returns a BytesURL tuple that holds a URI. This will encode all the information in the URL properly to ASCII using the rules a web browser would follow. It’s usually more interesting to directly call iri_to_uri() which will return a string. Return type werkzeug.urls.BaseURL
werkzeug.urls.index#werkzeug.urls.BaseURL.to_uri_tuple
to_url() Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling url_unparse() for this URL. Return type str
werkzeug.urls.index#werkzeug.urls.BaseURL.to_url
werkzeug.utils.bind_arguments(func, args, kwargs) Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments bind_arguments returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments. Parameters func – the function the arguments should be bound for. args – tuple of positional arguments. kwargs – a dict of keyword arguments. Returns a dict of bound keyword arguments. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use Signature.bind() instead.
werkzeug.utils.index#werkzeug.utils.bind_arguments
class werkzeug.filesystem.BrokenFilesystemWarning The warning used by Werkzeug to signal a broken filesystem. Will only be used once per runtime.
werkzeug.filesystem.index#werkzeug.filesystem.BrokenFilesystemWarning
class werkzeug.urls.BytesURL(scheme, netloc, path, query, fragment) Represents a parsed URL in bytes. Create new instance of _URLTuple(scheme, netloc, path, query, fragment) Parameters scheme (str) – netloc (str) – path (str) – query (str) – fragment (str) – decode(charset='utf-8', errors='replace') Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment. Parameters charset (str) – errors (str) – Return type werkzeug.urls.URL encode_netloc() Returns the netloc unchanged as bytes. Return type bytes
werkzeug.urls.index#werkzeug.urls.BytesURL
decode(charset='utf-8', errors='replace') Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment. Parameters charset (str) – errors (str) – Return type werkzeug.urls.URL
werkzeug.urls.index#werkzeug.urls.BytesURL.decode
encode_netloc() Returns the netloc unchanged as bytes. Return type bytes
werkzeug.urls.index#werkzeug.urls.BytesURL.encode_netloc
class werkzeug.utils.cached_property(fget, name=None, doc=None) A property() that is only evaluated once. Subsequent access returns the cached value. Setting the property sets the cached value. Deleting the property clears the cached value, accessing it again will evaluate it again. class Example: @cached_property def value(self): # calculate something important here return 42 e = Example() e.value # evaluates e.value # uses cache e.value = 16 # sets cache del e.value # clears cache The class must have a __dict__ for this to work. Changed in version 2.0: del obj.name clears the cached value. Parameters fget (Callable[[Any], Any]) – name (Optional[str]) – doc (Optional[str]) – Return type None
werkzeug.utils.index#werkzeug.utils.cached_property
CGI If all other deployment methods do not work, CGI will work for sure. CGI is supported by all major servers but usually has a less-than-optimal performance. This is also the way you can use a Werkzeug application on Google’s AppEngine, there however the execution does happen in a CGI-like environment. The application’s performance is unaffected because of that. Creating a .cgi file First you need to create the CGI application file. Let’s call it yourapplication.cgi: #!/usr/bin/python from wsgiref.handlers import CGIHandler from yourapplication import make_app application = make_app() CGIHandler().run(application) Server Setup Usually there are two ways to configure the server. Either just copy the .cgi into a cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the server point to the file directly. In Apache for example you can put something like this into the config: ScriptAlias /app /path/to/the/application.cgi For more information consult the documentation of your webserver.
werkzeug.deployment.cgi.index
class werkzeug.datastructures.CharsetAccept(values=()) Like Accept but with normalization for charsets.
werkzeug.datastructures.index#werkzeug.datastructures.CharsetAccept
werkzeug.security.check_password_hash(pwhash, password) Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns True if the password matched, False otherwise. Parameters pwhash (str) – a hashed string like returned by generate_password_hash(). password (str) – the plaintext password to compare against the hash. Return type bool
werkzeug.utils.index#werkzeug.security.check_password_hash
class werkzeug.test.Client(application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False) This class allows you to send requests to a wrapped application. The use_cookies parameter indicates whether cookies should be stored and sent for subsequent requests. This is True by default, but passing False will disable this behaviour. If you want to request some subdomain of your application you may set allow_subdomain_redirects to True as if not no external redirects are allowed. Changed in version 2.0: response_wrapper is always a subclass of :class:TestResponse. Changelog Changed in version 0.5: Added the use_cookies parameter. Parameters application (WSGIApplication) – response_wrapper (Optional[Type[Response]]) – use_cookies (bool) – allow_subdomain_redirects (bool) – Return type None set_cookie(server_name, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None, charset='utf-8') Sets a cookie in the client’s cookie jar. The server name is required and has to match the one that is also passed to the open call. Parameters server_name (str) – key (str) – value (str) – max_age (Optional[Union[datetime.timedelta, int]]) – expires (Optional[Union[str, datetime.datetime, int, float]]) – path (str) – domain (Optional[str]) – secure (bool) – httponly (bool) – samesite (Optional[str]) – charset (str) – Return type None delete_cookie(server_name, key, path='/', domain=None, secure=False, httponly=False, samesite=None) Deletes a cookie in the test client. Parameters server_name (str) – key (str) – path (str) – domain (Optional[str]) – secure (bool) – httponly (bool) – samesite (Optional[str]) – Return type None open(*args, as_tuple=False, buffered=False, follow_redirects=False, **kwargs) Generate an environ dict from the given arguments, make a request to the application using it, and return the response. Parameters args (Any) – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict. buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically. follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses. as_tuple (bool) – kwargs (Any) – Return type werkzeug.test.TestResponse Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead. Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed. Changelog Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper. Changed in version 0.5: Added the follow_redirects parameter. get(*args, **kw) Call open() with method set to GET. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse post(*args, **kw) Call open() with method set to POST. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse put(*args, **kw) Call open() with method set to PUT. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse delete(*args, **kw) Call open() with method set to DELETE. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse patch(*args, **kw) Call open() with method set to PATCH. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse options(*args, **kw) Call open() with method set to OPTIONS. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse head(*args, **kw) Call open() with method set to HEAD. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse trace(*args, **kw) Call open() with method set to TRACE. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client
delete(*args, **kw) Call open() with method set to DELETE. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.delete
delete_cookie(server_name, key, path='/', domain=None, secure=False, httponly=False, samesite=None) Deletes a cookie in the test client. Parameters server_name (str) – key (str) – path (str) – domain (Optional[str]) – secure (bool) – httponly (bool) – samesite (Optional[str]) – Return type None
werkzeug.test.index#werkzeug.test.Client.delete_cookie
get(*args, **kw) Call open() with method set to GET. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.get
head(*args, **kw) Call open() with method set to HEAD. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.head
open(*args, as_tuple=False, buffered=False, follow_redirects=False, **kwargs) Generate an environ dict from the given arguments, make a request to the application using it, and return the response. Parameters args (Any) – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict. buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically. follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses. as_tuple (bool) – kwargs (Any) – Return type werkzeug.test.TestResponse Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead. Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed. Changelog Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper. Changed in version 0.5: Added the follow_redirects parameter.
werkzeug.test.index#werkzeug.test.Client.open
options(*args, **kw) Call open() with method set to OPTIONS. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.options
patch(*args, **kw) Call open() with method set to PATCH. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.patch
post(*args, **kw) Call open() with method set to POST. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.post
put(*args, **kw) Call open() with method set to PUT. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.put
set_cookie(server_name, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None, charset='utf-8') Sets a cookie in the client’s cookie jar. The server name is required and has to match the one that is also passed to the open call. Parameters server_name (str) – key (str) – value (str) – max_age (Optional[Union[datetime.timedelta, int]]) – expires (Optional[Union[str, datetime.datetime, int, float]]) – path (str) – domain (Optional[str]) – secure (bool) – httponly (bool) – samesite (Optional[str]) – charset (str) – Return type None
werkzeug.test.index#werkzeug.test.Client.set_cookie
trace(*args, **kw) Call open() with method set to TRACE. Parameters args (Any) – kw (Any) – Return type werkzeug.test.TestResponse
werkzeug.test.index#werkzeug.test.Client.trace
class werkzeug.wsgi.ClosingIterator(iterable, callbacks=None) The WSGI specification requires that all middlewares and gateways respect the close callback of the iterable returned by the application. Because it is useful to add another close action to a returned iterable and adding a custom iterable is a boring task this class can be used for that: return ClosingIterator(app(environ, start_response), [cleanup_session, cleanup_locals]) If there is just one close function it can be passed instead of the list. A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started: try: return response(environ, start_response) finally: cleanup_session() cleanup_locals() Parameters iterable (Iterable[bytes]) – callbacks (Optional[Union[Callable[[], None], Iterable[Callable[[], None]]]]) – Return type None
werkzeug.wsgi.index#werkzeug.wsgi.ClosingIterator
class werkzeug.datastructures.CombinedMultiDict(dicts=None) A read only MultiDict that you can pass multiple MultiDict instances as sequence and it will combine the return values of all wrapped dicts: >>> from werkzeug.datastructures import CombinedMultiDict, MultiDict >>> post = MultiDict([('foo', 'bar')]) >>> get = MultiDict([('blub', 'blah')]) >>> combined = CombinedMultiDict([get, post]) >>> combined['foo'] 'bar' >>> combined['blub'] 'blah' This works for all read operations and will raise a TypeError for methods that usually change data which isn’t possible. From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions.
werkzeug.datastructures.index#werkzeug.datastructures.CombinedMultiDict
class werkzeug.datastructures.ContentRange(units, start, stop, length=None, on_update=None) Represents the content range header. Changelog New in version 0.7. property length The length of the range or None. set(start, stop, length=None, units='bytes') Simple method to update the ranges. property start The start point of the range or None. property stop The stop point of the range (non-inclusive) or None. Can only be None if also start is None. property units The units to use, usually β€œbytes” unset() Sets the units to None which indicates that the header should no longer be used.
werkzeug.datastructures.index#werkzeug.datastructures.ContentRange
set(start, stop, length=None, units='bytes') Simple method to update the ranges.
werkzeug.datastructures.index#werkzeug.datastructures.ContentRange.set
unset() Sets the units to None which indicates that the header should no longer be used.
werkzeug.datastructures.index#werkzeug.datastructures.ContentRange.unset
werkzeug.http.cookie_date(expires=None) Format a datetime object or timestamp into an RFC 2822 date string for Set-Cookie expires. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use http_date() instead. Parameters expires (Optional[Union[datetime.datetime, datetime.date, int, float, time.struct_time]]) – Return type str
werkzeug.http.index#werkzeug.http.cookie_date
werkzeug.test.create_environ(*args, **kwargs) Create a new WSGI environ dict based on the values passed. The first parameter should be the path of the request which defaults to β€˜/’. The second one can either be an absolute path (in that case the host is localhost:80) or a full path to the request with scheme, netloc port and the path to the script. This accepts the same arguments as the EnvironBuilder constructor. Changelog Changed in version 0.5: This function is now a thin wrapper over EnvironBuilder which was added in 0.5. The headers, environ_base, environ_overrides and charset parameters were added. Parameters args (Any) – kwargs (Any) – Return type WSGIEnvironment
werkzeug.test.index#werkzeug.test.create_environ
class werkzeug.debug.DebuggedApplication(app, evalex=False, request_key='werkzeug.request', console_path='/console', console_init_func=None, show_hidden_frames=False, pin_security=True, pin_logging=True) Enables debugging support for a given application: from werkzeug.debug import DebuggedApplication from myapp import app app = DebuggedApplication(app, evalex=True) The evalex keyword argument allows evaluating expressions in a traceback’s frame context. Parameters app (WSGIApplication) – the WSGI application to run debugged. evalex (bool) – enable exception evaluation feature (interactive debugging). This requires a non-forking server. request_key (str) – The key that points to the request object in ths environment. This parameter is ignored in current versions. console_path (str) – the URL for a general purpose console. console_init_func (Optional[Callable[[], Dict[str, Any]]]) – the function that is executed before starting the general purpose console. The return value is used as initial namespace. show_hidden_frames (bool) – by default hidden traceback frames are skipped. You can show them by setting this parameter to True. pin_security (bool) – can be used to disable the pin based security system. pin_logging (bool) – enables the logging of the pin system. Return type None
werkzeug.debug.index#werkzeug.debug.DebuggedApplication
class werkzeug.middleware.dispatcher.DispatcherMiddleware(app, mounts=None) Combine multiple applications as a single WSGI application. Requests are dispatched to an application based on the path it is mounted under. Parameters app (WSGIApplication) – The WSGI application to dispatch to if the request doesn’t match a mounted path. mounts (Optional[Dict[str, WSGIApplication]]) – Maps path prefixes to applications for dispatching. Return type None
werkzeug.middleware.dispatcher.index#werkzeug.middleware.dispatcher.DispatcherMiddleware
werkzeug.http.dump_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, charset='utf-8', sync_expires=True, max_size=4093, samesite=None) Create a Set-Cookie header without the Set-Cookie prefix. The return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. It’s tunneled through latin1 as required by PEP 3333. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It’s strongly recommended to not use non-ASCII values for the keys. Parameters 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. Additionally timedelta objects are accepted, too. 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]) – Use this 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) – The cookie will only be available via HTTPS httponly (bool) – disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. charset (str) – the encoding for string values. sync_expires (bool) – automatically set expires if max_age is defined but expires not. max_size (int) – Warn if the final header value exceeds this size. The default, 4093, should be safely supported by most browsers. Set to 0 to disable this check. samesite (Optional[str]) – Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site. key (str) – value (Union[bytes, str]) – Return type str Changelog Changed in version 1.0.0: The string 'None' is accepted for samesite.
werkzeug.http.index#werkzeug.http.dump_cookie
werkzeug.http.dump_header(iterable, allow_token=True) Dump an HTTP header again. This is the reversal of parse_list_header(), parse_set_header() and parse_dict_header(). This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_header({'foo': 'bar baz'}) 'foo="bar baz"' >>> dump_header(('foo', 'bar baz')) 'foo, "bar baz"' Parameters iterable (Union[Dict[str, Union[str, int]], Iterable[str]]) – the iterable or dict of values to quote. allow_token (bool) – if set to False tokens as values are disallowed. See quote_header_value() for more details. Return type str
werkzeug.http.index#werkzeug.http.dump_header
class werkzeug.routing.EndpointPrefix(prefix, rules) Prefixes all endpoints (which must be strings for this factory) with another string. This can be useful for sub applications: url_map = Map([ Rule('/', endpoint='index'), EndpointPrefix('blog/', [Submount('/blog', [ Rule('/', endpoint='index'), Rule('/entry/<entry_slug>', endpoint='show') ])]) ]) Parameters prefix (str) – rules (Iterable[Rule]) – Return type None
werkzeug.routing.index#werkzeug.routing.EndpointPrefix
class werkzeug.test.EnvironBuilder(path='/', base_url=None, query_string=None, method='GET', input_stream=None, content_type=None, content_length=None, errors_stream=None, multithread=False, multiprocess=False, run_once=False, headers=None, data=None, environ_base=None, environ_overrides=None, charset='utf-8', mimetype=None, json=None, auth=None) This class can be used to conveniently create a WSGI environment for testing purposes. It can be used to quickly create WSGI environments or request objects from arbitrary data. The signature of this class is also used in some other places as of Werkzeug 0.5 (create_environ(), Response.from_values(), Client.open()). Because of this most of the functionality is available through the constructor alone. Files and regular form data can be manipulated independently of each other with the form and files attributes, but are passed with the same argument to the constructor: data. data can be any of these values: a str or bytes object: The object is converted into an input_stream, the content_length is set and you have to provide a content_type. a dict or MultiDict: The keys have to be strings. The values have to be either any of the following objects, or a list of any of the following objects: a file-like object: These are converted into FileStorage objects automatically. a tuple: The add_file() method is called with the key and the unpacked tuple items as positional arguments. a str: The string is set as form data for the associated key. a file-like object: The object content is loaded in memory and then handled like a regular str or a bytes. Parameters path (str) – the path of the request. In the WSGI environment this will end up as PATH_INFO. If the query_string is not defined and there is a question mark in the path everything after it is used as query string. base_url (Optional[str]) – the base URL is a URL that is used to extract the WSGI URL scheme, host (server name + server port) and the script root (SCRIPT_NAME). query_string (Optional[Union[Mapping[str, str], str]]) – an optional string or dict with URL parameters. method (str) – the HTTP method to use, defaults to GET. input_stream (Optional[BinaryIO]) – an optional input stream. Do not specify this and data. As soon as an input stream is set you can’t modify args and files unless you set the input_stream to None again. content_type (Optional[str]) – The content type for the request. As of 0.5 you don’t have to provide this when specifying files and form data via data. content_length (Optional[int]) – The content length for the request. You don’t have to specify this when providing data via data. errors_stream (Optional[TextIO]) – an optional error stream that is used for wsgi.errors. Defaults to stderr. multithread (bool) – controls wsgi.multithread. Defaults to False. multiprocess (bool) – controls wsgi.multiprocess. Defaults to False. run_once (bool) – controls wsgi.run_once. Defaults to False. headers (Optional[Union[werkzeug.datastructures.Headers, Iterable[Tuple[str, str]]]]) – an optional list or Headers object of headers. data (Optional[Union[BinaryIO, str, bytes, Mapping[str, Any]]]) – a string or dict of form data or a file-object. See explanation above. json (Optional[Mapping[str, Any]]) – An object to be serialized and assigned to data. Defaults the content type to "application/json". Serialized with the function assigned to json_dumps. environ_base (Optional[Mapping[str, Any]]) – an optional dict of environment defaults. environ_overrides (Optional[Mapping[str, Any]]) – an optional dict of environment overrides. charset (str) – the charset used to encode string data. auth (Optional[Union[werkzeug.datastructures.Authorization, Tuple[str, str]]]) – An authorization object to use for the Authorization header value. A (username, password) tuple is a shortcut for Basic authorization. mimetype (Optional[str]) – Return type None Changed in version 2.0: REQUEST_URI and RAW_URI is the full raw URI including the query string, not only the path. Changed in version 2.0: The default request_class is Request instead of BaseRequest. New in version 2.0: Added the auth parameter. Changelog New in version 0.15: The json param and json_dumps() method. New in version 0.15: The environ has keys REQUEST_URI and RAW_URI containing the path before perecent-decoding. This is not part of the WSGI PEP, but many WSGI servers include it. Changed in version 0.6: path and base_url can now be unicode strings that are encoded with iri_to_uri(). server_protocol = 'HTTP/1.1' the server protocol to use. defaults to HTTP/1.1 wsgi_version = (1, 0) the wsgi version to use. defaults to (1, 0) request_class alias of werkzeug.wrappers.request.Request static json_dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) The serialization function used when json is passed. classmethod from_environ(environ, **kwargs) Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ. Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding. Changelog New in version 0.15. Parameters environ (WSGIEnvironment) – kwargs (Any) – Return type EnvironBuilder property base_url: str The base URL is used to extract the URL scheme, host name, port, and root path. property content_type: Optional[str] The content type for the request. Reflected from and to the headers. Do not set if you set files or form for auto detection. property mimetype: Optional[str] The mimetype (content type without charset etc.) Changelog New in version 0.14. property mimetype_params: Mapping[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.14. property content_length: Optional[int] The content length as integer. Reflected from and to the headers. Do not set if you set files or form for auto detection. property form: werkzeug.datastructures.MultiDict A MultiDict of form values. property files: werkzeug.datastructures.FileMultiDict A FileMultiDict of uploaded files. Use add_file() to add new files. property input_stream: Optional[BinaryIO] An optional input stream. This is mutually exclusive with setting form and files, setting it will clear those. Do not provide this if the method is not POST or another method that has a body. property query_string: str The query string. If you set this to a string args will no longer be available. property args: werkzeug.datastructures.MultiDict The URL arguments as MultiDict. property server_name: str The server name (read-only, use host to set) property server_port: int The server port as integer (read-only, use host to set) close() Closes all files. If you put real file objects into the files dict you can call this method to automatically close them all in one go. Return type None get_environ() Return the built environ. Changelog Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys. Return type WSGIEnvironment get_request(cls=None) Returns a request with the data. If the request class is not specified request_class is used. Parameters cls (Optional[Type[werkzeug.wrappers.request.Request]]) – The request wrapper to use. Return type werkzeug.wrappers.request.Request
werkzeug.test.index#werkzeug.test.EnvironBuilder
close() Closes all files. If you put real file objects into the files dict you can call this method to automatically close them all in one go. Return type None
werkzeug.test.index#werkzeug.test.EnvironBuilder.close
classmethod from_environ(environ, **kwargs) Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ. Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding. Changelog New in version 0.15. Parameters environ (WSGIEnvironment) – kwargs (Any) – Return type EnvironBuilder
werkzeug.test.index#werkzeug.test.EnvironBuilder.from_environ
get_environ() Return the built environ. Changelog Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys. Return type WSGIEnvironment
werkzeug.test.index#werkzeug.test.EnvironBuilder.get_environ
get_request(cls=None) Returns a request with the data. If the request class is not specified request_class is used. Parameters cls (Optional[Type[werkzeug.wrappers.request.Request]]) – The request wrapper to use. Return type werkzeug.wrappers.request.Request
werkzeug.test.index#werkzeug.test.EnvironBuilder.get_request
static json_dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) The serialization function used when json is passed.
werkzeug.test.index#werkzeug.test.EnvironBuilder.json_dumps
request_class alias of werkzeug.wrappers.request.Request
werkzeug.test.index#werkzeug.test.EnvironBuilder.request_class
server_protocol = 'HTTP/1.1' the server protocol to use. defaults to HTTP/1.1
werkzeug.test.index#werkzeug.test.EnvironBuilder.server_protocol
wsgi_version = (1, 0) the wsgi version to use. defaults to (1, 0)
werkzeug.test.index#werkzeug.test.EnvironBuilder.wsgi_version
class werkzeug.datastructures.EnvironHeaders(environ) Read only version of the headers from a WSGI environment. This provides the same interface as Headers and is constructed from a WSGI environment. From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions.
werkzeug.datastructures.index#werkzeug.datastructures.EnvironHeaders
class werkzeug.utils.environ_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None) Maps request attributes to environment variables. This works not only for the Werkzeug request object, but also any other class with an environ attribute: >>> class Test(object): ... environ = {'key': 'value'} ... test = environ_property('key') >>> var = Test() >>> var.test 'value' If you pass it a second value it’s used as default if the key does not exist, the third one can be a converter that takes a value and converts it. If it raises ValueError or TypeError the default value is used. If no default value is provided None is used. Per default the property is read only. You have to explicitly enable it by passing read_only=False to the constructor.
werkzeug.utils.index#werkzeug.utils.environ_property
werkzeug.utils.escape(s) Replace &, <, >, ", and ' with HTML-safe sequences. None is escaped to an empty string. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead. Parameters s (Any) – Return type str
werkzeug.utils.index#werkzeug.utils.escape
class werkzeug.datastructures.ETags(strong_etags=None, weak_etags=None, star_tag=False) A set that can be used to check if one etag is present in a collection of etags. as_set(include_weak=False) Convert the ETags object into a python set. Per default all the weak etags are not part of this set. contains(etag) Check if an etag is part of the set ignoring weak tags. It is also possible to use the in operator. contains_raw(etag) When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only. contains_weak(etag) Check if an etag is part of the set including weak and strong tags. is_strong(etag) Check if an etag is strong. is_weak(etag) Check if an etag is weak. to_header() Convert the etags set into a HTTP header string.
werkzeug.datastructures.index#werkzeug.datastructures.ETags
as_set(include_weak=False) Convert the ETags object into a python set. Per default all the weak etags are not part of this set.
werkzeug.datastructures.index#werkzeug.datastructures.ETags.as_set
contains(etag) Check if an etag is part of the set ignoring weak tags. It is also possible to use the in operator.
werkzeug.datastructures.index#werkzeug.datastructures.ETags.contains
contains_raw(etag) When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.
werkzeug.datastructures.index#werkzeug.datastructures.ETags.contains_raw
contains_weak(etag) Check if an etag is part of the set including weak and strong tags.
werkzeug.datastructures.index#werkzeug.datastructures.ETags.contains_weak
is_strong(etag) Check if an etag is strong.
werkzeug.datastructures.index#werkzeug.datastructures.ETags.is_strong
is_weak(etag) Check if an etag is weak.
werkzeug.datastructures.index#werkzeug.datastructures.ETags.is_weak
to_header() Convert the etags set into a HTTP header string.
werkzeug.datastructures.index#werkzeug.datastructures.ETags.to_header
werkzeug.wsgi.extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8', errors='werkzeug.url_quote', collapse_http_schemes=True) Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a string. The URLs might also be IRIs. If the path info could not be determined, None is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') '/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') '/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. Parameters environ_or_baseurl (Union[str, WSGIEnvironment]) – a WSGI environment dict, a base URL or base IRI. This is the root of the application. path_or_url (Union[str, werkzeug.urls._URLTuple]) – an absolute path from the server root, a relative path (in which case it’s the path info) or a full URL. charset (str) – the charset for byte data in URLs errors (str) – the error handling on decode collapse_http_schemes (bool) – if set to False the algorithm does not assume that http and https on the same server point to the same resource. Return type Optional[str] Changelog Changed in version 0.15: The errors parameter defaults to leaving invalid bytes quoted instead of replacing them. New in version 0.6.
werkzeug.wsgi.index#werkzeug.wsgi.extract_path_info
FastCGI A very popular deployment setup on servers like lighttpd and nginx is FastCGI. To use your WSGI application with any of them you will need a FastCGI server first. The most popular one is flup which we will use for this guide. Make sure to have it installed. Creating a .fcgi file First you need to create the FastCGI server file. Let’s call it yourapplication.fcgi: #!/usr/bin/python from flup.server.fcgi import WSGIServer from yourapplication import make_app if __name__ == '__main__': application = make_app() WSGIServer(application).run() This is enough for Apache to work, however ngingx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work you need to pass the path to the socket to the WSGIServer: WSGIServer(application, bindAddress='/path/to/fcgi.sock').run() The path has to be the exact same path you define in the server config. Save the yourapplication.fcgi file somewhere you will find it again. It makes sense to have that in /var/www/yourapplication or something similar. Make sure to set the executable bit on that file so that the servers can execute it: # chmod +x /var/www/yourapplication/yourapplication.fcgi Configuring lighttpd A basic FastCGI configuration for lighttpd looks like this: fastcgi.server = ("/yourapplication.fcgi" => (( "socket" => "/tmp/yourapplication-fcgi.sock", "bin-path" => "/var/www/yourapplication/yourapplication.fcgi", "check-local" => "disable", "max-procs" -> 1 )) ) alias.url = ( "/static/" => "/path/to/your/static" ) url.rewrite-once = ( "^(/static.*)$" => "$1", "^(/.*)$" => "/yourapplication.fcgi$1" Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication. See the Lighty docs for more information on FastCGI and Python. Configuring nginx Installing FastCGI applications on nginx is a bit tricky because by default some FastCGI parameters are not properly forwarded. A basic FastCGI configuration for nginx looks like this: location /yourapplication/ { include fastcgi_params; if ($uri ~ ^/yourapplication/(.*)?) { set $path_url $1; } fastcgi_param PATH_INFO $path_url; fastcgi_param SCRIPT_NAME /yourapplication; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; } This configuration binds the application to /yourapplication. If you want to have it in the URL root it’s a bit easier because you don’t have to figure out how to calculate PATH_INFO and SCRIPT_NAME: location /yourapplication/ { include fastcgi_params; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param SCRIPT_NAME ""; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; } Since Nginx doesn’t load FastCGI apps, you have to do it by yourself. You can either write an init.d script for that or execute it inside a screen session: $ screen $ /var/www/yourapplication/yourapplication.fcgi Debugging FastCGI deployments tend to be hard to debug on most webservers. Very often the only thing the server log tells you is something along the lines of β€œpremature end of headers”. In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand. This example assumes your application is called application.fcgi and that your webserver user is www-data: $ su www-data $ cd /var/www/yourapplication $ python application.fcgi Traceback (most recent call last): File "yourapplication.fcg", line 4, in <module> ImportError: No module named yourapplication In this case the error seems to be β€œyourapplication” not being on the python path. Common problems are: relative paths being used. Don’t rely on the current working directory the code depending on environment variables that are not set by the web server. different python interpreters being used.
werkzeug.deployment.fastcgi.index
class werkzeug.datastructures.FileMultiDict(mapping=None) A special MultiDict that has convenience methods to add files to it. This is used for EnvironBuilder and generally useful for unittesting. Changelog New in version 0.5. add_file(name, file, filename=None, content_type=None) Adds a new file to the dict. file can be a file name or a file-like or a FileStorage object. Parameters name – the name of the field. file – a filename or file-like object filename – an optional filename content_type – an optional content type
werkzeug.datastructures.index#werkzeug.datastructures.FileMultiDict
add_file(name, file, filename=None, content_type=None) Adds a new file to the dict. file can be a file name or a file-like or a FileStorage object. Parameters name – the name of the field. file – a filename or file-like object filename – an optional filename content_type – an optional content type
werkzeug.datastructures.index#werkzeug.datastructures.FileMultiDict.add_file
class werkzeug.datastructures.FileStorage(stream=None, filename=None, name=None, content_type=None, content_length=None, headers=None) The FileStorage class is a thin wrapper over incoming files. It is used by the request object to represent uploaded files. All the attributes of the wrapper stream are proxied by the file storage so it’s possible to do storage.read() instead of the long form storage.stream.read(). stream The input stream for the uploaded file. This usually points to an open temporary file. filename The filename of the file on the client. name The name of the form field. headers The multipart headers as Headers object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting. Changelog New in version 0.6. close() Close the underlying file if possible. property content_length The content-length sent in the header. Usually not available property content_type The content-type sent in the header. Usually not available property mimetype Like content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is text/HTML; charset=utf-8 the mimetype would be 'text/html'. Changelog New in version 0.7. property mimetype_params 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.7. save(dst, buffer_size=16384) Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. For secure file saving also have a look at secure_filename(). Parameters dst – a filename, os.PathLike, or open file object to write to. buffer_size – Passed as the length parameter of shutil.copyfileobj(). Changelog Changed in version 1.0: Supports pathlib.
werkzeug.datastructures.index#werkzeug.datastructures.FileStorage
close() Close the underlying file if possible.
werkzeug.datastructures.index#werkzeug.datastructures.FileStorage.close
filename The filename of the file on the client.
werkzeug.datastructures.index#werkzeug.datastructures.FileStorage.filename
headers The multipart headers as Headers object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting. Changelog New in version 0.6.
werkzeug.datastructures.index#werkzeug.datastructures.FileStorage.headers
name The name of the form field.
werkzeug.datastructures.index#werkzeug.datastructures.FileStorage.name
save(dst, buffer_size=16384) Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. For secure file saving also have a look at secure_filename(). Parameters dst – a filename, os.PathLike, or open file object to write to. buffer_size – Passed as the length parameter of shutil.copyfileobj(). Changelog Changed in version 1.0: Supports pathlib.
werkzeug.datastructures.index#werkzeug.datastructures.FileStorage.save
stream The input stream for the uploaded file. This usually points to an open temporary file.
werkzeug.datastructures.index#werkzeug.datastructures.FileStorage.stream
class werkzeug.wsgi.FileWrapper(file, buffer_size=8192) This class can be used to convert a file-like object into an iterable. It yields buffer_size blocks until the file is fully read. You should not use this class directly but rather use the wrap_file() function that uses the WSGI server’s file wrapper support if it’s available. Changelog New in version 0.5. If you’re using this object together with a Response you have to use the direct_passthrough mode. Parameters file (BinaryIO) – a file-like object with a read() method. buffer_size (int) – number of bytes for one iteration. Return type None
werkzeug.wsgi.index#werkzeug.wsgi.FileWrapper
werkzeug.utils.find_modules(import_path, include_packages=False, recursive=False) Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless include_packages is True. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. Parameters import_path (str) – the dotted name for the package to find child modules. include_packages (bool) – set to True if packages should be returned, too. recursive (bool) – set to True if recursion should happen. Returns generator Return type Iterator[str]
werkzeug.utils.index#werkzeug.utils.find_modules
class werkzeug.routing.FloatConverter(map, min=None, max=None, signed=False) This converter only accepts floating point values: Rule("/probability/<float:probability>") By default it only accepts unsigned, positive values. The signed parameter will enable signed, negative values. Rule("/offset/<float(signed=True):offset>") Parameters map (Map) – The Map. min (Optional[float]) – The minimal value. max (Optional[float]) – The maximal value. signed (bool) – Allow signed (negative) values. Return type None Changelog New in version 0.15: The signed parameter.
werkzeug.routing.index#werkzeug.routing.FloatConverter
class werkzeug.formparser.FormDataParser(stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True) This class implements parsing of form data for Werkzeug. By itself it can parse multipart and url encoded form data. It can be subclassed and extended but for most mimetypes it is a better idea to use the untouched stream and expose it as separate attributes on a request object. Changelog New in version 0.8. Parameters stream_factory (Optional[TStreamFactory]) – An optional callable that returns a new read and writeable file descriptor. This callable works the same as Response._get_file_stream(). charset (str) – The character set for URL and url encoded form data. errors (str) – The encoding error behavior. max_form_memory_size (Optional[int]) – the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an RequestEntityTooLarge exception is raised. max_content_length (Optional[int]) – If this is provided and the transmitted data is longer than this value an RequestEntityTooLarge exception is raised. cls (Optional[Type[werkzeug.datastructures.MultiDict]]) – an optional dict class to use. If this is not specified or None the default MultiDict is used. silent (bool) – If set to False parsing errors will not be caught. Return type None
werkzeug.http.index#werkzeug.formparser.FormDataParser
werkzeug.http.generate_etag(data) Generate an etag for some data. Changed in version 2.0: Use SHA-1. MD5 may not be available in some environments. Parameters data (bytes) – Return type str
werkzeug.http.index#werkzeug.http.generate_etag
werkzeug.security.generate_password_hash(password, method='pbkdf2:sha256', salt_length=16) Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that check_password_hash() can check the hash. The format for the hashed string looks like this: method$salt$hash This method can not generate unsalted passwords but it is possible to set param method=’plain’ in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to pbkdf2:method:iterations where iterations is optional: pbkdf2:sha256:80000$salt$hash pbkdf2:sha256$salt$hash Parameters password (str) – the password to hash. method (str) – the hash method to use (one that hashlib supports). Can optionally be in the format pbkdf2:method:iterations to enable PBKDF2. salt_length (int) – the length of the salt in letters. Return type str
werkzeug.utils.index#werkzeug.security.generate_password_hash
werkzeug.wsgi.get_content_length(environ) Returns the content length from the WSGI environment as integer. If it’s not available or chunked transfer encoding is used, None is returned. Changelog New in version 0.9. Parameters environ (WSGIEnvironment) – the WSGI environ to fetch the content length from. Return type Optional[int]
werkzeug.wsgi.index#werkzeug.wsgi.get_content_length