signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def make_alias_redirect_url(self, path, endpoint, values, method, query_args):
|
url = self.build(endpoint, values, method, append_unknown=False,<EOL>force_external=True)<EOL>if query_args:<EOL><INDENT>url += '<STR_LIT:?>' + self.encode_query_args(query_args)<EOL><DEDENT>assert url != path, '<STR_LIT>''<STR_LIT>'<EOL>return url<EOL>
|
Internally called to make an alias redirect URL.
|
f5873:c21:m9
|
def _partial_build(self, endpoint, values, method, append_unknown):
|
<EOL>if method is None:<EOL><INDENT>rv = self._partial_build(endpoint, values, self.default_method,<EOL>append_unknown)<EOL>if rv is not None:<EOL><INDENT>return rv<EOL><DEDENT><DEDENT>for rule in self.map._rules_by_endpoint.get(endpoint, ()):<EOL><INDENT>if rule.suitable_for(values, method):<EOL><INDENT>rv = rule.build(values, append_unknown)<EOL>if rv is not None:<EOL><INDENT>return rv<EOL><DEDENT><DEDENT><DEDENT>
|
Helper for :meth:`build`. Returns subdomain and path for the
rule that accepts this endpoint, values and method.
:internal:
|
f5873:c21:m10
|
def build(self, endpoint, values=None, method=None, force_external=False,<EOL>append_unknown=True):
|
self.map.update()<EOL>if values:<EOL><INDENT>if isinstance(values, MultiDict):<EOL><INDENT>valueiter = values.iteritems(multi=True)<EOL><DEDENT>else:<EOL><INDENT>valueiter = iteritems(values)<EOL><DEDENT>values = dict((k, v) for k, v in valueiter if v is not None)<EOL><DEDENT>else:<EOL><INDENT>values = {}<EOL><DEDENT>rv = self._partial_build(endpoint, values, method, append_unknown)<EOL>if rv is None:<EOL><INDENT>raise BuildError(endpoint, values, method)<EOL><DEDENT>domain_part, path = rv<EOL>host = self.get_host(domain_part)<EOL>if not force_external and (<EOL>(self.map.host_matching and host == self.server_name) or<EOL>(not self.map.host_matching and domain_part == self.subdomain)):<EOL><INDENT>return str(urljoin(self.script_name, '<STR_LIT>' + path.lstrip('<STR_LIT:/>')))<EOL><DEDENT>return str('<STR_LIT>' % (<EOL>self.url_scheme,<EOL>host,<EOL>self.script_name[:-<NUM_LIT:1>],<EOL>path.lstrip('<STR_LIT:/>')<EOL>))<EOL>
|
Building URLs works pretty much the other way round. Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for the placeholders.
The `build` function also accepts an argument called `force_external`
which, if you set it to `True` will force external URLs. Per default
external URLs (include the server name) will only be used if the
target URL is on a different subdomain.
>>> m = Map([
... Rule('/', endpoint='index'),
... Rule('/downloads/', endpoint='downloads/index'),
... Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.build("index", {})
'/'
>>> urls.build("downloads/show", {'id': 42})
'/downloads/42'
>>> urls.build("downloads/show", {'id': 42}, force_external=True)
'http://example.com/downloads/42'
Because URLs cannot contain non ASCII data you will always get
bytestrings back. Non ASCII characters are urlencoded with the
charset defined on the map instance.
Additional values are converted to unicode and appended to the URL as
URL querystring parameters:
>>> urls.build("index", {'q': 'My Searchstring'})
'/?q=My+Searchstring'
If a rule does not exist when building a `BuildError` exception is
raised.
The build method accepts an argument called `method` which allows you
to specify the method you want to have an URL built for if you have
different methods for the same endpoint specified.
.. versionadded:: 0.6
the `append_unknown` parameter was added.
:param endpoint: the endpoint of the URL to build.
:param values: the values for the URL to build. Unhandled values are
appended to the URL as query parameters.
:param method: the HTTP method for the rule if there are different
URLs for different methods on the same endpoint.
:param force_external: enforce full canonical external URLs.
:param append_unknown: unknown parameters are appended to the generated
URL as query string argument. Disable this
if you want the builder to ignore those.
|
f5873:c21:m11
|
def _run_wsgi_app(*args):
|
global _run_wsgi_app<EOL>from werkzeug.test import run_wsgi_app as _run_wsgi_app<EOL>return _run_wsgi_app(*args)<EOL>
|
This function replaces itself to ensure that the test module is not
imported unless required. DO NOT USE!
|
f5874:m0
|
def _warn_if_string(iterable):
|
if isinstance(iterable, string_types):<EOL><INDENT>from warnings import warn<EOL>warn(Warning('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'), stacklevel=<NUM_LIT:2>)<EOL><DEDENT>
|
Helper for the response objects to check if the iterable returned
to the WSGI server is not a string.
|
f5874:m1
|
@property<EOL><INDENT>def url_charset(self):<DEDENT>
|
return self.charset<EOL>
|
The charset that is assumed for URLs. Defaults to the value
of :attr:`charset`.
.. versionadded:: 0.6
|
f5874:c0:m2
|
@classmethod<EOL><INDENT>def from_values(cls, *args, **kwargs):<DEDENT>
|
from werkzeug.test import EnvironBuilder<EOL>charset = kwargs.pop('<STR_LIT>', cls.charset)<EOL>builder = EnvironBuilder(*args, **kwargs)<EOL>try:<EOL><INDENT>return builder.get_request(cls)<EOL><DEDENT>finally:<EOL><INDENT>builder.close()<EOL><DEDENT>
|
Create a new request object based on the values provided. If
environ is given missing values are filled from there. This method is
useful for small scripts when you need to simulate a request from an URL.
Do not use this method for unittesting, there is a full featured client
object (:class:`Client`) that allows to create multipart requests,
support for cookies etc.
This accepts the same options as the
:class:`~werkzeug.test.EnvironBuilder`.
.. versionchanged:: 0.5
This method now accepts the same arguments as
:class:`~werkzeug.test.EnvironBuilder`. Because of this the
`environ` parameter is now called `environ_overrides`.
:return: request object
|
f5874:c0:m3
|
@classmethod<EOL><INDENT>def application(cls, f):<DEDENT>
|
<EOL>def application(*args):<EOL><INDENT>request = cls(args[-<NUM_LIT:2>])<EOL>with request:<EOL><INDENT>return f(*args[:-<NUM_LIT:2>] + (request,))(*args[-<NUM_LIT:2>:])<EOL><DEDENT><DEDENT>return update_wrapper(application, f)<EOL>
|
Decorate a function as responder that accepts the request as first
argument. This works like the :func:`responder` decorator but the
function is passed the request object as first argument and the
request object will be closed automatically::
@Request.application
def my_wsgi_app(request):
return Response('Hello World!')
:param f: the WSGI callable to decorate
:return: a new WSGI callable
|
f5874:c0:m4
|
def _get_file_stream(self, total_content_length, content_type, filename=None,<EOL>content_length=None):
|
return default_stream_factory(total_content_length, content_type,<EOL>filename, content_length)<EOL>
|
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.
:param total_content_length: the total content length of all the
data in the request combined. This value
is guaranteed to be there.
:param content_type: the mimetype of the uploaded file.
:param filename: the filename of the uploaded file. May be `None`.
:param content_length: the length of this file. This value is usually
not provided because webbrowsers do not provide
this value.
|
f5874:c0:m5
|
@property<EOL><INDENT>def want_form_data_parsed(self):<DEDENT>
|
return bool(self.environ.get('<STR_LIT>'))<EOL>
|
Returns True if the request method carries content. As of
Werkzeug 0.9 this will be the case if a content type is transmitted.
.. versionadded:: 0.8
|
f5874:c0:m6
|
def make_form_data_parser(self):
|
return self.form_data_parser_class(self._get_file_stream,<EOL>self.charset,<EOL>self.encoding_errors,<EOL>self.max_form_memory_size,<EOL>self.max_content_length,<EOL>self.parameter_storage_class)<EOL>
|
Creates the form data parser. Instanciates the
:attr:`form_data_parser_class` with some parameters.
.. versionadded:: 0.8
|
f5874:c0:m7
|
def _load_form_data(self):
|
<EOL>if '<STR_LIT>' in self.__dict__:<EOL><INDENT>return<EOL><DEDENT>_assert_not_shallow(self)<EOL>if self.want_form_data_parsed:<EOL><INDENT>content_type = self.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>content_length = get_content_length(self.environ)<EOL>mimetype, options = parse_options_header(content_type)<EOL>parser = self.make_form_data_parser()<EOL>data = parser.parse(self.stream, mimetype,<EOL>content_length, options)<EOL><DEDENT>else:<EOL><INDENT>data = (self.stream, self.parameter_storage_class(),<EOL>self.parameter_storage_class())<EOL><DEDENT>d = self.__dict__<EOL>d['<STR_LIT>'], d['<STR_LIT>'], d['<STR_LIT>'] = data<EOL>
|
Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards.
.. versionadded:: 0.8
|
f5874:c0:m8
|
def close(self):
|
files = self.__dict__.get('<STR_LIT>')<EOL>for key, value in iter_multi_items(files or ()):<EOL><INDENT>value.close()<EOL><DEDENT>
|
Closes associated resources of this request object. This
closes all file handles explicitly. You can also use the request
object in a with statement with will automatically close it.
.. versionadded:: 0.9
|
f5874:c0:m9
|
@cached_property<EOL><INDENT>def stream(self):<DEDENT>
|
_assert_not_shallow(self)<EOL>return get_input_stream(self.environ)<EOL>
|
The stream to read incoming data from. Unlike :attr:`input_stream`
this stream is properly guarded that you can't accidentally read past
the length of the input. Werkzeug will internally always refer to
this stream to read data which makes it possible to wrap this
object with a stream that does filtering.
.. versionchanged:: 0.9
This stream is now always available but might be consumed by the
form parser later on. Previously the stream was only set if no
parsing happened.
|
f5874:c0:m12
|
@cached_property<EOL><INDENT>def args(self):<DEDENT>
|
return url_decode(wsgi_get_bytes(self.environ.get('<STR_LIT>', '<STR_LIT>')),<EOL>self.url_charset, errors=self.encoding_errors,<EOL>cls=self.parameter_storage_class)<EOL>
|
The parsed URL parameters. By default an
:class:`~werkzeug.datastructures.ImmutableMultiDict`
is returned from this function. This can be changed by setting
:attr:`parameter_storage_class` to a different type. This might
be necessary if the order of the form data is important.
|
f5874:c0:m13
|
def get_data(self, cache=True, as_text=False):
|
rv = getattr(self, '<STR_LIT>', None)<EOL>if rv is None:<EOL><INDENT>rv = self.stream.read()<EOL>if cache:<EOL><INDENT>self._cached_data = rv<EOL><DEDENT><DEDENT>if as_text:<EOL><INDENT>rv = rv.decode(self.charset, self.encoding_errors)<EOL><DEDENT>return rv<EOL>
|
This reads the buffered incoming data from the client into one
bytestring. By default this is cached but that behavior can be
changed by setting `cache` to `False`.
Usually it's a bad idea to call this method without checking the
content length first as a client could send dozens of megabytes or more
to cause memory problems on the server.
If `as_text` is set to `True` the return value will be a decoded
unicode string.
.. versionadded:: 0.9
|
f5874:c0:m15
|
@cached_property<EOL><INDENT>def form(self):<DEDENT>
|
self._load_form_data()<EOL>return self.form<EOL>
|
The form parameters. By default an
:class:`~werkzeug.datastructures.ImmutableMultiDict`
is returned from this function. This can be changed by setting
:attr:`parameter_storage_class` to a different type. This might
be necessary if the order of the form data is important.
|
f5874:c0:m16
|
@cached_property<EOL><INDENT>def values(self):<DEDENT>
|
args = []<EOL>for d in self.args, self.form:<EOL><INDENT>if not isinstance(d, MultiDict):<EOL><INDENT>d = MultiDict(d)<EOL><DEDENT>args.append(d)<EOL><DEDENT>return CombinedMultiDict(args)<EOL>
|
Combined multi dict for :attr:`args` and :attr:`form`.
|
f5874:c0:m17
|
@cached_property<EOL><INDENT>def files(self):<DEDENT>
|
self._load_form_data()<EOL>return self.files<EOL>
|
:class:`~werkzeug.datastructures.MultiDict` object containing
all uploaded files. Each key in :attr:`files` is the name from the
``<input type="file" name="">``. Each value in :attr:`files` is a
Werkzeug :class:`~werkzeug.datastructures.FileStorage` object.
Note that :attr:`files` will only contain data if the request method was
POST, PUT or PATCH and the ``<form>`` that posted to the request had
``enctype="multipart/form-data"``. It will be empty otherwise.
See the :class:`~werkzeug.datastructures.MultiDict` /
:class:`~werkzeug.datastructures.FileStorage` documentation for
more details about the used data structure.
|
f5874:c0:m18
|
@cached_property<EOL><INDENT>def cookies(self):<DEDENT>
|
return parse_cookie(self.environ, self.charset,<EOL>self.encoding_errors,<EOL>cls=self.dict_storage_class)<EOL>
|
Read only access to the retrieved cookie values as dictionary.
|
f5874:c0:m19
|
@cached_property<EOL><INDENT>def headers(self):<DEDENT>
|
return EnvironHeaders(self.environ)<EOL>
|
The headers from the WSGI environ as immutable
:class:`~werkzeug.datastructures.EnvironHeaders`.
|
f5874:c0:m20
|
@cached_property<EOL><INDENT>def path(self):<DEDENT>
|
raw_path = wsgi_decoding_dance(self.environ.get('<STR_LIT>') or '<STR_LIT>',<EOL>self.charset, self.encoding_errors)<EOL>return '<STR_LIT:/>' + raw_path.lstrip('<STR_LIT:/>')<EOL>
|
Requested path as unicode. This works a bit like the regular path
info in the WSGI environment but will always include a leading slash,
even if the URL root is accessed.
|
f5874:c0:m21
|
@cached_property<EOL><INDENT>def full_path(self):<DEDENT>
|
return self.path + u'<STR_LIT:?>' + to_unicode(self.query_string, self.url_charset)<EOL>
|
Requested path as unicode, including the query string.
|
f5874:c0:m22
|
@cached_property<EOL><INDENT>def script_root(self):<DEDENT>
|
raw_path = wsgi_decoding_dance(self.environ.get('<STR_LIT>') or '<STR_LIT>',<EOL>self.charset, self.encoding_errors)<EOL>return raw_path.rstrip('<STR_LIT:/>')<EOL>
|
The root path of the script without the trailing slash.
|
f5874:c0:m23
|
@cached_property<EOL><INDENT>def url(self):<DEDENT>
|
return get_current_url(self.environ,<EOL>trusted_hosts=self.trusted_hosts)<EOL>
|
The reconstructed current URL
|
f5874:c0:m24
|
@cached_property<EOL><INDENT>def base_url(self):<DEDENT>
|
return get_current_url(self.environ, strip_querystring=True,<EOL>trusted_hosts=self.trusted_hosts)<EOL>
|
Like :attr:`url` but without the querystring
|
f5874:c0:m25
|
@cached_property<EOL><INDENT>def url_root(self):<DEDENT>
|
return get_current_url(self.environ, True,<EOL>trusted_hosts=self.trusted_hosts)<EOL>
|
The full URL root (with hostname), this is the application root.
|
f5874:c0:m26
|
@cached_property<EOL><INDENT>def host_url(self):<DEDENT>
|
return get_current_url(self.environ, host_only=True,<EOL>trusted_hosts=self.trusted_hosts)<EOL>
|
Just the host with scheme.
|
f5874:c0:m27
|
@cached_property<EOL><INDENT>def host(self):<DEDENT>
|
return get_host(self.environ, trusted_hosts=self.trusted_hosts)<EOL>
|
Just the host including the port if available.
|
f5874:c0:m28
|
@cached_property<EOL><INDENT>def access_route(self):<DEDENT>
|
if '<STR_LIT>' in self.environ:<EOL><INDENT>addr = self.environ['<STR_LIT>'].split('<STR_LIT:U+002C>')<EOL>return self.list_storage_class([x.strip() for x in addr])<EOL><DEDENT>elif '<STR_LIT>' in self.environ:<EOL><INDENT>return self.list_storage_class([self.environ['<STR_LIT>']])<EOL><DEDENT>return self.list_storage_class()<EOL>
|
If a forwarded header exists this is a list of all ip addresses
from the client ip to the last proxy server.
|
f5874:c0:m29
|
@property<EOL><INDENT>def remote_addr(self):<DEDENT>
|
return self.environ.get('<STR_LIT>')<EOL>
|
The remote address of the client.
|
f5874:c0:m30
|
def call_on_close(self, func):
|
self._on_close.append(func)<EOL>return func<EOL>
|
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.
.. versionadded:: 0.6
|
f5874:c1:m1
|
@classmethod<EOL><INDENT>def force_type(cls, response, environ=None):<DEDENT>
|
if not isinstance(response, BaseResponse):<EOL><INDENT>if environ is None:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>response = BaseResponse(*_run_wsgi_app(response, environ))<EOL><DEDENT>response.__class__ = cls<EOL>return response<EOL>
|
Enforce that the WSGI response is a response object of the current
type. Werkzeug will use the :class:`BaseResponse` internally in many
situations like the exceptions. If you call :meth:`get_response` on an
exception you will get back a regular :class:`BaseResponse` 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!
:param response: a response object or wsgi application.
:param environ: a WSGI environment object.
:return: a response object.
|
f5874:c1:m3
|
@classmethod<EOL><INDENT>def from_app(cls, app, environ, buffered=False):<DEDENT>
|
return cls(*_run_wsgi_app(app, environ, buffered))<EOL>
|
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.
:param app: the WSGI application to execute.
:param environ: the WSGI environment to execute against.
:param buffered: set to `True` to enforce buffering.
:return: a response object.
|
f5874:c1:m4
|
def get_data(self, as_text=False):
|
self._ensure_sequence()<EOL>rv = b'<STR_LIT>'.join(self.iter_encoded())<EOL>if as_text:<EOL><INDENT>rv = rv.decode(self.charset)<EOL><DEDENT>return rv<EOL>
|
The string representation of the request body. Whenever you call
this property the request iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
:attr:`implicit_sequence_conversion` to `False`.
If `as_text` is set to `True` the return value will be a decoded
unicode string.
.. versionadded:: 0.9
|
f5874:c1:m9
|
def set_data(self, value):
|
<EOL>if isinstance(value, text_type):<EOL><INDENT>value = value.encode(self.charset)<EOL><DEDENT>else:<EOL><INDENT>value = bytes(value)<EOL><DEDENT>self.response = [value]<EOL>if self.automatically_set_content_length:<EOL><INDENT>self.headers['<STR_LIT>'] = str(len(value))<EOL><DEDENT>
|
Sets a new string as response. The value set must either by a
unicode or bytestring. If a unicode string is set it's encoded
automatically to the charset of the response (utf-8 by default).
.. versionadded:: 0.9
|
f5874:c1:m10
|
def calculate_content_length(self):
|
try:<EOL><INDENT>self._ensure_sequence()<EOL><DEDENT>except RuntimeError:<EOL><INDENT>return None<EOL><DEDENT>return sum(len(x) for x in self.response)<EOL>
|
Returns the content length if available or `None` otherwise.
|
f5874:c1:m11
|
def _ensure_sequence(self, mutable=False):
|
if self.is_sequence:<EOL><INDENT>if mutable and not isinstance(self.response, list):<EOL><INDENT>self.response = list(self.response)<EOL><DEDENT>return<EOL><DEDENT>if self.direct_passthrough:<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if not self.implicit_sequence_conversion:<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self.make_sequence()<EOL>
|
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.
.. versionadded:: 0.6
|
f5874:c1:m12
|
def make_sequence(self):
|
if not self.is_sequence:<EOL><INDENT>close = getattr(self.response, '<STR_LIT>', None)<EOL>self.response = list(self.iter_encoded())<EOL>if close is not None:<EOL><INDENT>self.call_on_close(close)<EOL><DEDENT><DEDENT>
|
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.
.. versionadded:: 0.6
|
f5874:c1:m13
|
def iter_encoded(self):
|
charset = self.charset<EOL>if __debug__:<EOL><INDENT>_warn_if_string(self.response)<EOL><DEDENT>return _iter_encoded(self.response, self.charset)<EOL>
|
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
:attr:`direct_passthrough` was activated.
|
f5874:c1:m14
|
def set_cookie(self, key, value='<STR_LIT>', max_age=None, expires=None,<EOL>path='<STR_LIT:/>', domain=None, secure=None, httponly=False):
|
self.headers.add('<STR_LIT>', dump_cookie(key, value, max_age,<EOL>expires, path, domain, secure, httponly,<EOL>self.charset))<EOL>
|
Sets a cookie. The parameters are the same as in the cookie `Morsel`
object in the Python standard library but it accepts unicode data, too.
:param key: the key (name) of the cookie to be set.
:param value: the value of the cookie.
:param max_age: should be a number of seconds, or `None` (default) if
the cookie should last only as long as the client's
browser session.
:param expires: should be a `datetime` object or UNIX timestamp.
:param domain: 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.
:param path: limits the cookie to a given path, per default it will
span the whole domain.
|
f5874:c1:m15
|
def delete_cookie(self, key, path='<STR_LIT:/>', domain=None):
|
self.set_cookie(key, expires=<NUM_LIT:0>, max_age=<NUM_LIT:0>, path=path, domain=domain)<EOL>
|
Delete a cookie. Fails silently if key doesn't exist.
:param key: the key (name) of the cookie to be deleted.
:param path: if the cookie that should be deleted was limited to a
path, the path has to be defined here.
:param domain: if the cookie that should be deleted was limited to a
domain, that domain has to be defined here.
|
f5874:c1:m16
|
@property<EOL><INDENT>def is_streamed(self):<DEDENT>
|
try:<EOL><INDENT>len(self.response)<EOL><DEDENT>except TypeError:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
|
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.
|
f5874:c1:m17
|
@property<EOL><INDENT>def is_sequence(self):<DEDENT>
|
return isinstance(self.response, (tuple, list))<EOL>
|
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.
.. versionadded:: 0.6
|
f5874:c1:m18
|
def close(self):
|
if hasattr(self.response, '<STR_LIT>'):<EOL><INDENT>self.response.close()<EOL><DEDENT>for func in self._on_close:<EOL><INDENT>func()<EOL><DEDENT>
|
Close the wrapped response if possible. You can also use the object
in a with statement which will automatically close it.
.. versionadded:: 0.9
Can now be used in a with statement.
|
f5874:c1:m19
|
def freeze(self):
|
<EOL>self.response = list(self.iter_encoded())<EOL>self.headers['<STR_LIT>'] = str(sum(map(len, self.response)))<EOL>
|
Call this method if you want to make your response object ready for
being pickled. This buffers the generator if there is one. It will
also set the `Content-Length` header to the length of the body.
.. versionchanged:: 0.6
The `Content-Length` header is now set.
|
f5874:c1:m22
|
def get_wsgi_headers(self, environ):
|
headers = Headers(self.headers)<EOL>location = None<EOL>content_location = None<EOL>content_length = None<EOL>status = self.status_code<EOL>for key, value in headers:<EOL><INDENT>ikey = key.lower()<EOL>if ikey == u'<STR_LIT:location>':<EOL><INDENT>location = value<EOL><DEDENT>elif ikey == u'<STR_LIT>':<EOL><INDENT>content_location = value<EOL><DEDENT>elif ikey == u'<STR_LIT>':<EOL><INDENT>content_length = value<EOL><DEDENT><DEDENT>if location is not None:<EOL><INDENT>old_location = location<EOL>if isinstance(location, text_type):<EOL><INDENT>location = iri_to_uri(location)<EOL><DEDENT>if self.autocorrect_location_header:<EOL><INDENT>current_url = get_current_url(environ, root_only=True)<EOL>if isinstance(current_url, text_type):<EOL><INDENT>current_url = iri_to_uri(current_url)<EOL><DEDENT>location = url_join(current_url, location)<EOL><DEDENT>if location != old_location:<EOL><INDENT>headers['<STR_LIT>'] = location<EOL><DEDENT><DEDENT>if content_location is not None andisinstance(content_location, text_type):<EOL><INDENT>headers['<STR_LIT>'] = iri_to_uri(content_location)<EOL><DEDENT>if <NUM_LIT:100> <= status < <NUM_LIT:200> or status == <NUM_LIT>:<EOL><INDENT>headers['<STR_LIT>'] = content_length = u'<STR_LIT:0>'<EOL><DEDENT>elif status == <NUM_LIT>:<EOL><INDENT>remove_entity_headers(headers)<EOL><DEDENT>if self.automatically_set_content_length andself.is_sequence and content_length is None and status != <NUM_LIT>:<EOL><INDENT>try:<EOL><INDENT>content_length = sum(len(to_bytes(x, '<STR_LIT:ascii>')) for x in self.response)<EOL><DEDENT>except UnicodeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>headers['<STR_LIT>'] = str(content_length)<EOL><DEDENT><DEDENT>return headers<EOL>
|
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.
.. versionchanged:: 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.
:param environ: the WSGI environment of the request.
:return: returns a new :class:`~werkzeug.datastructures.Headers`
object.
|
f5874:c1:m23
|
def get_app_iter(self, environ):
|
status = self.status_code<EOL>if environ['<STR_LIT>'] == '<STR_LIT>' or<NUM_LIT:100> <= status < <NUM_LIT:200> or status in (<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>iterable = ()<EOL><DEDENT>elif self.direct_passthrough:<EOL><INDENT>if __debug__:<EOL><INDENT>_warn_if_string(self.response)<EOL><DEDENT>return self.response<EOL><DEDENT>else:<EOL><INDENT>iterable = self.iter_encoded()<EOL><DEDENT>return ClosingIterator(iterable, self.close)<EOL>
|
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.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: a response iterable.
|
f5874:c1:m24
|
def get_wsgi_response(self, environ):
|
headers = self.get_wsgi_headers(environ)<EOL>app_iter = self.get_app_iter(environ)<EOL>return app_iter, self.status, headers.to_wsgi_list()<EOL>
|
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.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: an ``(app_iter, status, headers)`` tuple.
|
f5874:c1:m25
|
def __call__(self, environ, start_response):
|
app_iter, status, headers = self.get_wsgi_response(environ)<EOL>start_response(status, headers)<EOL>return app_iter<EOL>
|
Process this response as WSGI application.
:param environ: the WSGI environment.
:param start_response: the response callable provided by the WSGI
server.
:return: an application iterator
|
f5874:c1:m26
|
@cached_property<EOL><INDENT>def accept_mimetypes(self):<DEDENT>
|
return parse_accept_header(self.environ.get('<STR_LIT>'), MIMEAccept)<EOL>
|
List of mimetypes this client supports as
:class:`~werkzeug.datastructures.MIMEAccept` object.
|
f5874:c2:m0
|
@cached_property<EOL><INDENT>def accept_charsets(self):<DEDENT>
|
return parse_accept_header(self.environ.get('<STR_LIT>'),<EOL>CharsetAccept)<EOL>
|
List of charsets this client supports as
:class:`~werkzeug.datastructures.CharsetAccept` object.
|
f5874:c2:m1
|
@cached_property<EOL><INDENT>def accept_encodings(self):<DEDENT>
|
return parse_accept_header(self.environ.get('<STR_LIT>'))<EOL>
|
List of encodings this client accepts. Encodings in a HTTP term
are compression encodings such as gzip. For charsets have a look at
:attr:`accept_charset`.
|
f5874:c2:m2
|
@cached_property<EOL><INDENT>def accept_languages(self):<DEDENT>
|
return parse_accept_header(self.environ.get('<STR_LIT>'),<EOL>LanguageAccept)<EOL>
|
List of languages this client accepts as
:class:`~werkzeug.datastructures.LanguageAccept` object.
.. versionchanged 0.5
In previous versions this was a regular
:class:`~werkzeug.datastructures.Accept` object.
|
f5874:c2:m3
|
@cached_property<EOL><INDENT>def cache_control(self):<DEDENT>
|
cache_control = self.environ.get('<STR_LIT>')<EOL>return parse_cache_control_header(cache_control, None,<EOL>RequestCacheControl)<EOL>
|
A :class:`~werkzeug.datastructures.RequestCacheControl` object
for the incoming cache control headers.
|
f5874:c3:m0
|
@cached_property<EOL><INDENT>def if_match(self):<DEDENT>
|
return parse_etags(self.environ.get('<STR_LIT>'))<EOL>
|
An object containing all the etags in the `If-Match` header.
:rtype: :class:`~werkzeug.datastructures.ETags`
|
f5874:c3:m1
|
@cached_property<EOL><INDENT>def if_none_match(self):<DEDENT>
|
return parse_etags(self.environ.get('<STR_LIT>'))<EOL>
|
An object containing all the etags in the `If-None-Match` header.
:rtype: :class:`~werkzeug.datastructures.ETags`
|
f5874:c3:m2
|
@cached_property<EOL><INDENT>def if_modified_since(self):<DEDENT>
|
return parse_date(self.environ.get('<STR_LIT>'))<EOL>
|
The parsed `If-Modified-Since` header as datetime object.
|
f5874:c3:m3
|
@cached_property<EOL><INDENT>def if_unmodified_since(self):<DEDENT>
|
return parse_date(self.environ.get('<STR_LIT>'))<EOL>
|
The parsed `If-Unmodified-Since` header as datetime object.
|
f5874:c3:m4
|
@cached_property<EOL><INDENT>def if_range(self):<DEDENT>
|
return parse_if_range_header(self.environ.get('<STR_LIT>'))<EOL>
|
The parsed `If-Range` header.
.. versionadded:: 0.7
:rtype: :class:`~werkzeug.datastructures.IfRange`
|
f5874:c3:m5
|
@cached_property<EOL><INDENT>def range(self):<DEDENT>
|
return parse_range_header(self.environ.get('<STR_LIT>'))<EOL>
|
The parsed `Range` header.
.. versionadded:: 0.7
:rtype: :class:`~werkzeug.datastructures.Range`
|
f5874:c3:m6
|
@cached_property<EOL><INDENT>def user_agent(self):<DEDENT>
|
from werkzeug.useragents import UserAgent<EOL>return UserAgent(self.environ)<EOL>
|
The current user agent.
|
f5874:c4:m0
|
@cached_property<EOL><INDENT>def authorization(self):<DEDENT>
|
header = self.environ.get('<STR_LIT>')<EOL>return parse_authorization_header(header)<EOL>
|
The `Authorization` object in parsed form.
|
f5874:c5:m0
|
@property<EOL><INDENT>def cache_control(self):<DEDENT>
|
def on_update(cache_control):<EOL><INDENT>if not cache_control and '<STR_LIT>' in self.headers:<EOL><INDENT>del self.headers['<STR_LIT>']<EOL><DEDENT>elif cache_control:<EOL><INDENT>self.headers['<STR_LIT>'] = cache_control.to_header()<EOL><DEDENT><DEDENT>return parse_cache_control_header(self.headers.get('<STR_LIT>'),<EOL>on_update,<EOL>ResponseCacheControl)<EOL>
|
The Cache-Control general-header field is used to specify
directives that MUST be obeyed by all caching mechanisms along the
request/response chain.
|
f5874:c7:m0
|
def make_conditional(self, request_or_environ):
|
environ = _get_environ(request_or_environ)<EOL>if environ['<STR_LIT>'] in ('<STR_LIT:GET>', '<STR_LIT>'):<EOL><INDENT>if '<STR_LIT:date>' not in self.headers:<EOL><INDENT>self.headers['<STR_LIT>'] = http_date()<EOL><DEDENT>if '<STR_LIT>' not in self.headers:<EOL><INDENT>length = self.calculate_content_length()<EOL>if length is not None:<EOL><INDENT>self.headers['<STR_LIT>'] = length<EOL><DEDENT><DEDENT>if not is_resource_modified(environ, self.headers.get('<STR_LIT>'), None,<EOL>self.headers.get('<STR_LIT>')):<EOL><INDENT>self.status_code = <NUM_LIT><EOL><DEDENT><DEDENT>return self<EOL>
|
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.
It does not remove the body of the response because that's something
the :meth:`__call__` function does for us automatically.
Returns self so that you can do ``return resp.make_conditional(req)``
but modifies the object in-place.
:param request_or_environ: a request object or WSGI environment to be
used to make the response conditional
against.
|
f5874:c7:m1
|
def add_etag(self, overwrite=False, weak=False):
|
if overwrite or '<STR_LIT>' not in self.headers:<EOL><INDENT>self.set_etag(generate_etag(self.get_data()), weak)<EOL><DEDENT>
|
Add an etag for the current response if there is none yet.
|
f5874:c7:m2
|
def set_etag(self, etag, weak=False):
|
self.headers['<STR_LIT>'] = quote_etag(etag, weak)<EOL>
|
Set the etag, and override the old one if there was one.
|
f5874:c7:m3
|
def get_etag(self):
|
return unquote_etag(self.headers.get('<STR_LIT>'))<EOL>
|
Return a tuple in the form ``(etag, is_weak)``. If there is no
ETag the return value is ``(None, None)``.
|
f5874:c7:m4
|
def freeze(self, no_etag=False):
|
if not no_etag:<EOL><INDENT>self.add_etag()<EOL><DEDENT>super(ETagResponseMixin, self).freeze()<EOL>
|
Call this method if you want to make your response object ready for
pickeling. This buffers the generator if there is one. This also
sets the etag unless `no_etag` is set to `True`.
|
f5874:c7:m5
|
@cached_property<EOL><INDENT>def stream(self):<DEDENT>
|
return ResponseStream(self)<EOL>
|
The response iterable as write-only stream.
|
f5874:c9:m0
|
@cached_property<EOL><INDENT>def content_length(self):<DEDENT>
|
return get_content_length(self.environ)<EOL>
|
The Content-Length entity-header field indicates the size of the
entity-body in bytes or, in the case of the HEAD method, the size of
the entity-body that would have been sent had the request been a
GET.
|
f5874:c10:m0
|
@property<EOL><INDENT>def mimetype(self):<DEDENT>
|
self._parse_content_type()<EOL>return self._parsed_content_type[<NUM_LIT:0>]<EOL>
|
Like :attr:`content_type` but without parameters (eg, without
charset, type etc.). For example if the content
type is ``text/html; charset=utf-8`` the mimetype would be
``'text/html'``.
|
f5874:c10:m2
|
@property<EOL><INDENT>def mimetype_params(self):<DEDENT>
|
self._parse_content_type()<EOL>return self._parsed_content_type[<NUM_LIT:1>]<EOL>
|
The mimetype parameters as dict. For example if the content
type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
|
f5874:c10:m3
|
@cached_property<EOL><INDENT>def pragma(self):<DEDENT>
|
return parse_set_header(self.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>
|
The Pragma general-header field is used to include
implementation-specific directives that might apply to any recipient
along the request/response chain. All pragma directives specify
optional behavior from the viewpoint of the protocol; however, some
systems MAY require that behavior be consistent with the directives.
|
f5874:c10:m4
|
@property<EOL><INDENT>def www_authenticate(self):<DEDENT>
|
def on_update(www_auth):<EOL><INDENT>if not www_auth and '<STR_LIT>' in self.headers:<EOL><INDENT>del self.headers['<STR_LIT>']<EOL><DEDENT>elif www_auth:<EOL><INDENT>self.headers['<STR_LIT>'] = www_auth.to_header()<EOL><DEDENT><DEDENT>header = self.headers.get('<STR_LIT>')<EOL>return parse_www_authenticate_header(header, on_update)<EOL>
|
The `WWW-Authenticate` header in a parsed form.
|
f5874:c12:m0
|
def stream_encode_multipart(values, use_tempfile=True, threshold=<NUM_LIT> * <NUM_LIT>,<EOL>boundary=None, charset='<STR_LIT:utf-8>'):
|
if boundary is None:<EOL><INDENT>boundary = '<STR_LIT>' % (time(), random())<EOL><DEDENT>_closure = [BytesIO(), <NUM_LIT:0>, False]<EOL>if use_tempfile:<EOL><INDENT>def write_binary(string):<EOL><INDENT>stream, total_length, on_disk = _closure<EOL>if on_disk:<EOL><INDENT>stream.write(string)<EOL><DEDENT>else:<EOL><INDENT>length = len(string)<EOL>if length + _closure[<NUM_LIT:1>] <= threshold:<EOL><INDENT>stream.write(string)<EOL><DEDENT>else:<EOL><INDENT>new_stream = TemporaryFile('<STR_LIT>')<EOL>new_stream.write(stream.getvalue())<EOL>new_stream.write(string)<EOL>_closure[<NUM_LIT:0>] = new_stream<EOL>_closure[<NUM_LIT:2>] = True<EOL><DEDENT>_closure[<NUM_LIT:1>] = total_length + length<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>write_binary = _closure[<NUM_LIT:0>].write<EOL><DEDENT>def write(string):<EOL><INDENT>write_binary(string.encode(charset))<EOL><DEDENT>if not isinstance(values, MultiDict):<EOL><INDENT>values = MultiDict(values)<EOL><DEDENT>for key, values in iterlists(values):<EOL><INDENT>for value in values:<EOL><INDENT>write('<STR_LIT>' %<EOL>(boundary, key))<EOL>reader = getattr(value, '<STR_LIT>', None)<EOL>if reader is not None:<EOL><INDENT>filename = getattr(value, '<STR_LIT:filename>',<EOL>getattr(value, '<STR_LIT:name>', None))<EOL>content_type = getattr(value, '<STR_LIT>', None)<EOL>if content_type is None:<EOL><INDENT>content_type = filename andmimetypes.guess_type(filename)[<NUM_LIT:0>] or'<STR_LIT>'<EOL><DEDENT>if filename is not None:<EOL><INDENT>write('<STR_LIT>' % filename)<EOL><DEDENT>else:<EOL><INDENT>write('<STR_LIT:\r\n>')<EOL><DEDENT>write('<STR_LIT>' % content_type)<EOL>while <NUM_LIT:1>:<EOL><INDENT>chunk = reader(<NUM_LIT>)<EOL>if not chunk:<EOL><INDENT>break<EOL><DEDENT>write_binary(chunk)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(value, string_types):<EOL><INDENT>value = to_native(value, charset)<EOL><DEDENT>else:<EOL><INDENT>value = str(value)<EOL><DEDENT>write('<STR_LIT>' + value)<EOL><DEDENT>write('<STR_LIT:\r\n>')<EOL><DEDENT><DEDENT>write('<STR_LIT>' % boundary)<EOL>length = int(_closure[<NUM_LIT:0>].tell())<EOL>_closure[<NUM_LIT:0>].seek(<NUM_LIT:0>)<EOL>return _closure[<NUM_LIT:0>], length, boundary<EOL>
|
Encode a dict of values (either strings or file descriptors or
:class:`FileStorage` objects.) into a multipart encoded string stored
in a file descriptor.
|
f5876:m0
|
def encode_multipart(values, boundary=None, charset='<STR_LIT:utf-8>'):
|
stream, length, boundary = stream_encode_multipart(<EOL>values, use_tempfile=False, boundary=boundary, charset=charset)<EOL>return boundary, stream.read()<EOL>
|
Like `stream_encode_multipart` but returns a tuple in the form
(``boundary``, ``data``) where data is a bytestring.
|
f5876:m1
|
def File(fd, filename=None, mimetype=None):
|
from warnings import warn<EOL>warn(DeprecationWarning('<STR_LIT>'<EOL>'<STR_LIT>'))<EOL>return FileStorage(fd, filename=filename, content_type=mimetype)<EOL>
|
Backwards compat.
|
f5876:m2
|
def _iter_data(data):
|
if isinstance(data, MultiDict):<EOL><INDENT>for key, values in iterlists(data):<EOL><INDENT>for value in values:<EOL><INDENT>yield key, value<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for key, values in iteritems(data):<EOL><INDENT>if isinstance(values, list):<EOL><INDENT>for value in values:<EOL><INDENT>yield key, value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield key, values<EOL><DEDENT><DEDENT><DEDENT>
|
Iterates over a dict or multidict yielding all keys and values.
This is used to iterate over the data passed to the
:class:`EnvironBuilder`.
|
f5876:m3
|
def create_environ(*args, **kwargs):
|
builder = EnvironBuilder(*args, **kwargs)<EOL>try:<EOL><INDENT>return builder.get_environ()<EOL><DEDENT>finally:<EOL><INDENT>builder.close()<EOL><DEDENT>
|
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 :class:`EnvironBuilder`
constructor.
.. versionchanged:: 0.5
This function is now a thin wrapper over :class:`EnvironBuilder` which
was added in 0.5. The `headers`, `environ_base`, `environ_overrides`
and `charset` parameters were added.
|
f5876:m4
|
def run_wsgi_app(app, environ, buffered=False):
|
environ = _get_environ(environ)<EOL>response = []<EOL>buffer = []<EOL>def start_response(status, headers, exc_info=None):<EOL><INDENT>if exc_info is not None:<EOL><INDENT>reraise(*exc_info)<EOL><DEDENT>response[:] = [status, headers]<EOL>return buffer.append<EOL><DEDENT>app_iter = app(environ, start_response)<EOL>if buffered:<EOL><INDENT>close_func = getattr(app_iter, '<STR_LIT>', None)<EOL>try:<EOL><INDENT>app_iter = list(app_iter)<EOL><DEDENT>finally:<EOL><INDENT>if close_func is not None:<EOL><INDENT>close_func()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>while not response:<EOL><INDENT>buffer.append(next(app_iter))<EOL><DEDENT>if buffer:<EOL><INDENT>close_func = getattr(app_iter, '<STR_LIT>', None)<EOL>app_iter = chain(buffer, app_iter)<EOL>if close_func is not None:<EOL><INDENT>app_iter = ClosingIterator(app_iter, close_func)<EOL><DEDENT><DEDENT><DEDENT>return app_iter, response[<NUM_LIT:0>], Headers(response[<NUM_LIT:1>])<EOL>
|
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.
:param app: the application to execute.
:param buffered: set to `True` to enforce buffering.
:return: tuple in the form ``(app_iter, status, headers)``
|
f5876:m5
|
def inject_wsgi(self, environ):
|
cvals = []<EOL>for cookie in self:<EOL><INDENT>cvals.append('<STR_LIT>' % (cookie.name, cookie.value))<EOL><DEDENT>if cvals:<EOL><INDENT>environ['<STR_LIT>'] = '<STR_LIT>'.join(cvals)<EOL><DEDENT>
|
Inject the cookies as client headers into the server's wsgi
environment.
|
f5876:c2:m0
|
def extract_wsgi(self, environ, headers):
|
self.extract_cookies(<EOL>_TestCookieResponse(headers),<EOL>U2Request(get_current_url(environ)),<EOL>)<EOL>
|
Extract the server's set-cookie headers as cookies into the
cookie jar.
|
f5876:c2:m1
|
def _add_file_from_data(self, key, value):
|
if isinstance(value, tuple):<EOL><INDENT>self.files.add_file(key, *value)<EOL><DEDENT>elif isinstance(value, dict):<EOL><INDENT>from warnings import warn<EOL>warn(DeprecationWarning('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'), stacklevel=<NUM_LIT:2>)<EOL>value = dict(value)<EOL>mimetype = value.pop('<STR_LIT>', None)<EOL>if mimetype is not None:<EOL><INDENT>value['<STR_LIT>'] = mimetype<EOL><DEDENT>self.files.add_file(key, **value)<EOL><DEDENT>else:<EOL><INDENT>self.files.add_file(key, value)<EOL><DEDENT>
|
Called in the EnvironBuilder to add files from the data dict.
|
f5876:c3:m1
|
@property<EOL><INDENT>def server_name(self):<DEDENT>
|
return self.host.split('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>
|
The server name (read-only, use :attr:`host` to set)
|
f5876:c3:m15
|
@property<EOL><INDENT>def server_port(self):<DEDENT>
|
pieces = self.host.split('<STR_LIT::>', <NUM_LIT:1>)<EOL>if len(pieces) == <NUM_LIT:2> and pieces[<NUM_LIT:1>].isdigit():<EOL><INDENT>return int(pieces[<NUM_LIT:1>])<EOL><DEDENT>elif self.url_scheme == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>return <NUM_LIT><EOL>
|
The server port as integer (read-only, use :attr:`host` to set)
|
f5876:c3:m16
|
def close(self):
|
if self.closed:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>files = itervalues(self.files)<EOL><DEDENT>except AttributeError:<EOL><INDENT>files = ()<EOL><DEDENT>for f in files:<EOL><INDENT>try:<EOL><INDENT>f.close()<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.closed = True<EOL>
|
Closes all files. If you put real :class:`file` objects into the
:attr:`files` dict you can call this method to automatically close
them all in one go.
|
f5876:c3:m18
|
def get_environ(self):
|
input_stream = self.input_stream<EOL>content_length = self.content_length<EOL>content_type = self.content_type<EOL>if input_stream is not None:<EOL><INDENT>start_pos = input_stream.tell()<EOL>input_stream.seek(<NUM_LIT:0>, <NUM_LIT:2>)<EOL>end_pos = input_stream.tell()<EOL>input_stream.seek(start_pos)<EOL>content_length = end_pos - start_pos<EOL><DEDENT>elif content_type == '<STR_LIT>':<EOL><INDENT>values = CombinedMultiDict([self.form, self.files])<EOL>input_stream, content_length, boundary =stream_encode_multipart(values, charset=self.charset)<EOL>content_type += '<STR_LIT>' % boundary<EOL><DEDENT>elif content_type == '<STR_LIT>':<EOL><INDENT>values = url_encode(self.form, charset=self.charset)<EOL>values = values.encode('<STR_LIT:ascii>')<EOL>content_length = len(values)<EOL>input_stream = BytesIO(values)<EOL><DEDENT>else:<EOL><INDENT>input_stream = _empty_stream<EOL><DEDENT>result = {}<EOL>if self.environ_base:<EOL><INDENT>result.update(self.environ_base)<EOL><DEDENT>def _path_encode(x):<EOL><INDENT>return wsgi_encoding_dance(url_unquote(x, self.charset), self.charset)<EOL><DEDENT>qs = wsgi_encoding_dance(self.query_string)<EOL>result.update({<EOL>'<STR_LIT>': self.method,<EOL>'<STR_LIT>': _path_encode(self.script_root),<EOL>'<STR_LIT>': _path_encode(self.path),<EOL>'<STR_LIT>': qs,<EOL>'<STR_LIT>': self.server_name,<EOL>'<STR_LIT>': str(self.server_port),<EOL>'<STR_LIT>': self.host,<EOL>'<STR_LIT>': self.server_protocol,<EOL>'<STR_LIT>': content_type or '<STR_LIT>',<EOL>'<STR_LIT>': str(content_length or '<STR_LIT:0>'),<EOL>'<STR_LIT>': self.wsgi_version,<EOL>'<STR_LIT>': self.url_scheme,<EOL>'<STR_LIT>': input_stream,<EOL>'<STR_LIT>': self.errors_stream,<EOL>'<STR_LIT>': self.multithread,<EOL>'<STR_LIT>': self.multiprocess,<EOL>'<STR_LIT>': self.run_once<EOL>})<EOL>for key, value in self.headers.to_wsgi_list():<EOL><INDENT>result['<STR_LIT>' % key.upper().replace('<STR_LIT:->', '<STR_LIT:_>')] = value<EOL><DEDENT>if self.environ_overrides:<EOL><INDENT>result.update(self.environ_overrides)<EOL><DEDENT>return result<EOL>
|
Return the built environ.
|
f5876:c3:m19
|
def get_request(self, cls=None):
|
if cls is None:<EOL><INDENT>cls = self.request_class<EOL><DEDENT>return cls(self.get_environ())<EOL>
|
Returns a request with the data. If the request class is not
specified :attr:`request_class` is used.
:param cls: The request wrapper to use.
|
f5876:c3:m20
|
def set_cookie(self, server_name, key, value='<STR_LIT>', max_age=None,<EOL>expires=None, path='<STR_LIT:/>', domain=None, secure=None,<EOL>httponly=False, charset='<STR_LIT:utf-8>'):
|
assert self.cookie_jar is not None, '<STR_LIT>'<EOL>header = dump_cookie(key, value, max_age, expires, path, domain,<EOL>secure, httponly, charset)<EOL>environ = create_environ(path, base_url='<STR_LIT>' + server_name)<EOL>headers = [('<STR_LIT>', header)]<EOL>self.cookie_jar.extract_wsgi(environ, headers)<EOL>
|
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.
|
f5876:c5:m1
|
def delete_cookie(self, server_name, key, path='<STR_LIT:/>', domain=None):
|
self.set_cookie(server_name, key, expires=<NUM_LIT:0>, max_age=<NUM_LIT:0>,<EOL>path=path, domain=domain)<EOL>
|
Deletes a cookie in the test client.
|
f5876:c5:m2
|
def run_wsgi_app(self, environ, buffered=False):
|
if self.cookie_jar is not None:<EOL><INDENT>self.cookie_jar.inject_wsgi(environ)<EOL><DEDENT>rv = run_wsgi_app(self.application, environ, buffered=buffered)<EOL>if self.cookie_jar is not None:<EOL><INDENT>self.cookie_jar.extract_wsgi(environ, rv[<NUM_LIT:2>])<EOL><DEDENT>return rv<EOL>
|
Runs the wrapped WSGI app with the given environment.
|
f5876:c5:m3
|
def resolve_redirect(self, response, new_location, environ, buffered=False):
|
scheme, netloc, script_root, qs, anchor = url_parse(new_location)<EOL>base_url = url_unparse((scheme, netloc, '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')).rstrip('<STR_LIT:/>') + '<STR_LIT:/>'<EOL>cur_server_name = netloc.split('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:0>].split('<STR_LIT:.>')<EOL>real_server_name = get_host(environ).rsplit('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:0>].split('<STR_LIT:.>')<EOL>if self.allow_subdomain_redirects:<EOL><INDENT>allowed = cur_server_name[-len(real_server_name):] == real_server_name<EOL><DEDENT>else:<EOL><INDENT>allowed = cur_server_name == real_server_name<EOL><DEDENT>if not allowed:<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>' % self.__class__)<EOL><DEDENT>old_response_wrapper = self.response_wrapper<EOL>self.response_wrapper = None<EOL>try:<EOL><INDENT>return self.open(path=script_root, base_url=base_url,<EOL>query_string=qs, as_tuple=True,<EOL>buffered=buffered)<EOL><DEDENT>finally:<EOL><INDENT>self.response_wrapper = old_response_wrapper<EOL><DEDENT>
|
Resolves a single redirect and triggers the request again
directly on this redirect client.
|
f5876:c5:m4
|
def open(self, *args, **kwargs):
|
as_tuple = kwargs.pop('<STR_LIT>', False)<EOL>buffered = kwargs.pop('<STR_LIT>', False)<EOL>follow_redirects = kwargs.pop('<STR_LIT>', False)<EOL>environ = None<EOL>if not kwargs and len(args) == <NUM_LIT:1>:<EOL><INDENT>if isinstance(args[<NUM_LIT:0>], EnvironBuilder):<EOL><INDENT>environ = args[<NUM_LIT:0>].get_environ()<EOL><DEDENT>elif isinstance(args[<NUM_LIT:0>], dict):<EOL><INDENT>environ = args[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if environ is None:<EOL><INDENT>builder = EnvironBuilder(*args, **kwargs)<EOL>try:<EOL><INDENT>environ = builder.get_environ()<EOL><DEDENT>finally:<EOL><INDENT>builder.close()<EOL><DEDENT><DEDENT>response = self.run_wsgi_app(environ, buffered=buffered)<EOL>redirect_chain = []<EOL>while <NUM_LIT:1>:<EOL><INDENT>status_code = int(response[<NUM_LIT:1>].split(None, <NUM_LIT:1>)[<NUM_LIT:0>])<EOL>if status_code not in (<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)or not follow_redirects:<EOL><INDENT>break<EOL><DEDENT>new_location = response[<NUM_LIT:2>]['<STR_LIT:location>']<EOL>new_redirect_entry = (new_location, status_code)<EOL>if new_redirect_entry in redirect_chain:<EOL><INDENT>raise ClientRedirectError('<STR_LIT>')<EOL><DEDENT>redirect_chain.append(new_redirect_entry)<EOL>environ, response = self.resolve_redirect(response, new_location,<EOL>environ, buffered=buffered)<EOL><DEDENT>if self.response_wrapper is not None:<EOL><INDENT>response = self.response_wrapper(*response)<EOL><DEDENT>if as_tuple:<EOL><INDENT>return environ, response<EOL><DEDENT>return response<EOL>
|
Takes the same arguments as the :class:`EnvironBuilder` class with
some additions: You can provide a :class:`EnvironBuilder` or a WSGI
environment as only argument instead of the :class:`EnvironBuilder`
arguments and two optional keyword arguments (`as_tuple`, `buffered`)
that change the type of the return value or the way the application is
executed.
.. versionchanged:: 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` now instead of
`mimetype`. This change was made for consistency with
:class:`werkzeug.FileWrapper`.
The `follow_redirects` parameter was added to :func:`open`.
Additional parameters:
:param as_tuple: Returns a tuple in the form ``(environ, result)``
:param buffered: Set this to True to buffer the application run.
This will automatically close the application for
you as well.
:param follow_redirects: Set this to True if the `Client` should
follow HTTP redirects.
|
f5876:c5:m5
|
def get(self, *args, **kw):
|
kw['<STR_LIT>'] = '<STR_LIT:GET>'<EOL>return self.open(*args, **kw)<EOL>
|
Like open but method is enforced to GET.
|
f5876:c5:m6
|
def patch(self, *args, **kw):
|
kw['<STR_LIT>'] = '<STR_LIT>'<EOL>return self.open(*args, **kw)<EOL>
|
Like open but method is enforced to PATCH.
|
f5876:c5:m7
|
def post(self, *args, **kw):
|
kw['<STR_LIT>'] = '<STR_LIT:POST>'<EOL>return self.open(*args, **kw)<EOL>
|
Like open but method is enforced to POST.
|
f5876:c5:m8
|
def head(self, *args, **kw):
|
kw['<STR_LIT>'] = '<STR_LIT>'<EOL>return self.open(*args, **kw)<EOL>
|
Like open but method is enforced to HEAD.
|
f5876:c5:m9
|
def put(self, *args, **kw):
|
kw['<STR_LIT>'] = '<STR_LIT>'<EOL>return self.open(*args, **kw)<EOL>
|
Like open but method is enforced to PUT.
|
f5876:c5:m10
|
def delete(self, *args, **kw):
|
kw['<STR_LIT>'] = '<STR_LIT>'<EOL>return self.open(*args, **kw)<EOL>
|
Like open but method is enforced to DELETE.
|
f5876:c5:m11
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.