index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
42,131 |
werkzeug.exceptions
|
get_response
|
Get a response object. If one was passed to the exception
it's returned directly.
:param environ: the optional environ for the request. This
can be used to modify the response depending
on how the request looked like.
:return: a :class:`Response` object or a subclass thereof.
|
def get_response(
self,
environ: WSGIEnvironment | WSGIRequest | None = None,
scope: dict[str, t.Any] | None = None,
) -> Response:
"""Get a response object. If one was passed to the exception
it's returned directly.
:param environ: the optional environ for the request. This
can be used to modify the response depending
on how the request looked like.
:return: a :class:`Response` object or a subclass thereof.
"""
from .wrappers.response import Response as WSGIResponse # noqa: F811
if self.response is not None:
return self.response
if environ is not None:
environ = _get_environ(environ)
headers = self.get_headers(environ, scope)
return WSGIResponse(self.get_body(environ, scope), self.code, headers)
|
(self, environ: 'WSGIEnvironment | WSGIRequest | None' = None, scope: 'dict[str, t.Any] | None' = None) -> 'Response'
|
42,132 |
werkzeug.datastructures.headers
|
Headers
|
An object that stores some headers. It has a dict-like interface,
but is ordered, can store the same key multiple times, and iterating
yields ``(key, value)`` pairs instead of only keys.
This data structure is useful if you want a nicer way to handle WSGI
headers which are stored as tuples in a list.
From Werkzeug 0.3 onwards, the :exc:`KeyError` raised by this class is
also a subclass of the :class:`~exceptions.BadRequest` HTTP exception
and will render a page for a ``400 BAD REQUEST`` if caught in a
catch-all for HTTP exceptions.
Headers is mostly compatible with the Python :class:`wsgiref.headers.Headers`
class, with the exception of `__getitem__`. :mod:`wsgiref` will return
`None` for ``headers['missing']``, whereas :class:`Headers` will raise
a :class:`KeyError`.
To create a new ``Headers`` object, pass it a list, dict, or
other ``Headers`` object with default values. These values are
validated the same way values added later are.
:param defaults: The list of default values for the :class:`Headers`.
.. versionchanged:: 2.1.0
Default values are validated the same as values added later.
.. versionchanged:: 0.9
This data structure now stores unicode values similar to how the
multi dicts do it. The main difference is that bytes can be set as
well which will automatically be latin1 decoded.
.. versionchanged:: 0.9
The :meth:`linked` function was removed without replacement as it
was an API that does not support the changes to the encoding model.
|
class Headers:
"""An object that stores some headers. It has a dict-like interface,
but is ordered, can store the same key multiple times, and iterating
yields ``(key, value)`` pairs instead of only keys.
This data structure is useful if you want a nicer way to handle WSGI
headers which are stored as tuples in a list.
From Werkzeug 0.3 onwards, the :exc:`KeyError` raised by this class is
also a subclass of the :class:`~exceptions.BadRequest` HTTP exception
and will render a page for a ``400 BAD REQUEST`` if caught in a
catch-all for HTTP exceptions.
Headers is mostly compatible with the Python :class:`wsgiref.headers.Headers`
class, with the exception of `__getitem__`. :mod:`wsgiref` will return
`None` for ``headers['missing']``, whereas :class:`Headers` will raise
a :class:`KeyError`.
To create a new ``Headers`` object, pass it a list, dict, or
other ``Headers`` object with default values. These values are
validated the same way values added later are.
:param defaults: The list of default values for the :class:`Headers`.
.. versionchanged:: 2.1.0
Default values are validated the same as values added later.
.. versionchanged:: 0.9
This data structure now stores unicode values similar to how the
multi dicts do it. The main difference is that bytes can be set as
well which will automatically be latin1 decoded.
.. versionchanged:: 0.9
The :meth:`linked` function was removed without replacement as it
was an API that does not support the changes to the encoding model.
"""
def __init__(self, defaults=None):
self._list = []
if defaults is not None:
self.extend(defaults)
def __getitem__(self, key, _get_mode=False):
if not _get_mode:
if isinstance(key, int):
return self._list[key]
elif isinstance(key, slice):
return self.__class__(self._list[key])
if not isinstance(key, str):
raise BadRequestKeyError(key)
ikey = key.lower()
for k, v in self._list:
if k.lower() == ikey:
return v
# micro optimization: if we are in get mode we will catch that
# exception one stack level down so we can raise a standard
# key error instead of our special one.
if _get_mode:
raise KeyError()
raise BadRequestKeyError(key)
def __eq__(self, other):
def lowered(item):
return (item[0].lower(),) + item[1:]
return other.__class__ is self.__class__ and set(
map(lowered, other._list)
) == set(map(lowered, self._list))
__hash__ = None
def get(self, key, default=None, type=None):
"""Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the default as if the value was not
found:
>>> d = Headers([('Content-Length', '42')])
>>> d.get('Content-Length', type=int)
42
:param key: The key to be looked up.
:param default: The default value to be returned if the key can't
be looked up. If not further specified `None` is
returned.
:param type: A callable that is used to cast the value in the
:class:`Headers`. If a :exc:`ValueError` is raised
by this callable the default value is returned.
.. versionchanged:: 3.0
The ``as_bytes`` parameter was removed.
.. versionchanged:: 0.9
The ``as_bytes`` parameter was added.
"""
try:
rv = self.__getitem__(key, _get_mode=True)
except KeyError:
return default
if type is None:
return rv
try:
return type(rv)
except ValueError:
return default
def getlist(self, key, type=None):
"""Return the list of items for a given key. If that key is not in the
:class:`Headers`, the return value will be an empty list. Just like
:meth:`get`, :meth:`getlist` accepts a `type` parameter. All items will
be converted with the callable defined there.
:param key: The key to be looked up.
:param type: A callable that is used to cast the value in the
:class:`Headers`. If a :exc:`ValueError` is raised
by this callable the value will be removed from the list.
:return: a :class:`list` of all the values for the key.
.. versionchanged:: 3.0
The ``as_bytes`` parameter was removed.
.. versionchanged:: 0.9
The ``as_bytes`` parameter was added.
"""
ikey = key.lower()
result = []
for k, v in self:
if k.lower() == ikey:
if type is not None:
try:
v = type(v)
except ValueError:
continue
result.append(v)
return result
def get_all(self, name):
"""Return a list of all the values for the named field.
This method is compatible with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.get_all` method.
"""
return self.getlist(name)
def items(self, lower=False):
for key, value in self:
if lower:
key = key.lower()
yield key, value
def keys(self, lower=False):
for key, _ in self.items(lower):
yield key
def values(self):
for _, value in self.items():
yield value
def extend(self, *args, **kwargs):
"""Extend headers in this object with items from another object
containing header items as well as keyword arguments.
To replace existing keys instead of extending, use
:meth:`update` instead.
If provided, the first argument can be another :class:`Headers`
object, a :class:`MultiDict`, :class:`dict`, or iterable of
pairs.
.. versionchanged:: 1.0
Support :class:`MultiDict`. Allow passing ``kwargs``.
"""
if len(args) > 1:
raise TypeError(f"update expected at most 1 arguments, got {len(args)}")
if args:
for key, value in iter_multi_items(args[0]):
self.add(key, value)
for key, value in iter_multi_items(kwargs):
self.add(key, value)
def __delitem__(self, key, _index_operation=True):
if _index_operation and isinstance(key, (int, slice)):
del self._list[key]
return
key = key.lower()
new = []
for k, v in self._list:
if k.lower() != key:
new.append((k, v))
self._list[:] = new
def remove(self, key):
"""Remove a key.
:param key: The key to be removed.
"""
return self.__delitem__(key, _index_operation=False)
def pop(self, key=None, default=_missing):
"""Removes and returns a key or index.
:param key: The key to be popped. If this is an integer the item at
that position is removed, if it's a string the value for
that key is. If the key is omitted or `None` the last
item is removed.
:return: an item.
"""
if key is None:
return self._list.pop()
if isinstance(key, int):
return self._list.pop(key)
try:
rv = self[key]
self.remove(key)
except KeyError:
if default is not _missing:
return default
raise
return rv
def popitem(self):
"""Removes a key or index and returns a (key, value) item."""
return self.pop()
def __contains__(self, key):
"""Check if a key is present."""
try:
self.__getitem__(key, _get_mode=True)
except KeyError:
return False
return True
def __iter__(self):
"""Yield ``(key, value)`` tuples."""
return iter(self._list)
def __len__(self):
return len(self._list)
def add(self, _key, _value, **kw):
"""Add a new header tuple to the list.
Keyword arguments can specify additional parameters for the header
value, with underscores converted to dashes::
>>> d = Headers()
>>> d.add('Content-Type', 'text/plain')
>>> d.add('Content-Disposition', 'attachment', filename='foo.png')
The keyword argument dumping uses :func:`dump_options_header`
behind the scenes.
.. versionadded:: 0.4.1
keyword arguments were added for :mod:`wsgiref` compatibility.
"""
if kw:
_value = _options_header_vkw(_value, kw)
_value = _str_header_value(_value)
self._list.append((_key, _value))
def add_header(self, _key, _value, **_kw):
"""Add a new header tuple to the list.
An alias for :meth:`add` for compatibility with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.add_header` method.
"""
self.add(_key, _value, **_kw)
def clear(self):
"""Clears all headers."""
del self._list[:]
def set(self, _key, _value, **kw):
"""Remove all header tuples for `key` and add a new one. The newly
added key either appears at the end of the list if there was no
entry or replaces the first one.
Keyword arguments can specify additional parameters for the header
value, with underscores converted to dashes. See :meth:`add` for
more information.
.. versionchanged:: 0.6.1
:meth:`set` now accepts the same arguments as :meth:`add`.
:param key: The key to be inserted.
:param value: The value to be inserted.
"""
if kw:
_value = _options_header_vkw(_value, kw)
_value = _str_header_value(_value)
if not self._list:
self._list.append((_key, _value))
return
listiter = iter(self._list)
ikey = _key.lower()
for idx, (old_key, _old_value) in enumerate(listiter):
if old_key.lower() == ikey:
# replace first occurrence
self._list[idx] = (_key, _value)
break
else:
self._list.append((_key, _value))
return
self._list[idx + 1 :] = [t for t in listiter if t[0].lower() != ikey]
def setlist(self, key, values):
"""Remove any existing values for a header and add new ones.
:param key: The header key to set.
:param values: An iterable of values to set for the key.
.. versionadded:: 1.0
"""
if values:
values_iter = iter(values)
self.set(key, next(values_iter))
for value in values_iter:
self.add(key, value)
else:
self.remove(key)
def setdefault(self, key, default):
"""Return the first value for the key if it is in the headers,
otherwise set the header to the value given by ``default`` and
return that.
:param key: The header key to get.
:param default: The value to set for the key if it is not in the
headers.
"""
if key in self:
return self[key]
self.set(key, default)
return default
def setlistdefault(self, key, default):
"""Return the list of values for the key if it is in the
headers, otherwise set the header to the list of values given
by ``default`` and return that.
Unlike :meth:`MultiDict.setlistdefault`, modifying the returned
list will not affect the headers.
:param key: The header key to get.
:param default: An iterable of values to set for the key if it
is not in the headers.
.. versionadded:: 1.0
"""
if key not in self:
self.setlist(key, default)
return self.getlist(key)
def __setitem__(self, key, value):
"""Like :meth:`set` but also supports index/slice based setting."""
if isinstance(key, (slice, int)):
if isinstance(key, int):
value = [value]
value = [(k, _str_header_value(v)) for (k, v) in value]
if isinstance(key, int):
self._list[key] = value[0]
else:
self._list[key] = value
else:
self.set(key, value)
def update(self, *args, **kwargs):
"""Replace headers in this object with items from another
headers object and keyword arguments.
To extend existing keys instead of replacing, use :meth:`extend`
instead.
If provided, the first argument can be another :class:`Headers`
object, a :class:`MultiDict`, :class:`dict`, or iterable of
pairs.
.. versionadded:: 1.0
"""
if len(args) > 1:
raise TypeError(f"update expected at most 1 arguments, got {len(args)}")
if args:
mapping = args[0]
if isinstance(mapping, (Headers, MultiDict)):
for key in mapping.keys():
self.setlist(key, mapping.getlist(key))
elif isinstance(mapping, dict):
for key, value in mapping.items():
if isinstance(value, (list, tuple)):
self.setlist(key, value)
else:
self.set(key, value)
else:
for key, value in mapping:
self.set(key, value)
for key, value in kwargs.items():
if isinstance(value, (list, tuple)):
self.setlist(key, value)
else:
self.set(key, value)
def to_wsgi_list(self):
"""Convert the headers into a list suitable for WSGI.
:return: list
"""
return list(self)
def copy(self):
return self.__class__(self._list)
def __copy__(self):
return self.copy()
def __str__(self):
"""Returns formatted headers suitable for HTTP transmission."""
strs = []
for key, value in self.to_wsgi_list():
strs.append(f"{key}: {value}")
strs.append("\r\n")
return "\r\n".join(strs)
def __repr__(self):
return f"{type(self).__name__}({list(self)!r})"
|
(defaults=None)
|
42,133 |
werkzeug.datastructures.headers
|
__contains__
|
Check if a key is present.
|
def __contains__(self, key):
"""Check if a key is present."""
try:
self.__getitem__(key, _get_mode=True)
except KeyError:
return False
return True
|
(self, key)
|
42,135 |
werkzeug.datastructures.headers
|
__delitem__
| null |
def __delitem__(self, key, _index_operation=True):
if _index_operation and isinstance(key, (int, slice)):
del self._list[key]
return
key = key.lower()
new = []
for k, v in self._list:
if k.lower() != key:
new.append((k, v))
self._list[:] = new
|
(self, key, _index_operation=True)
|
42,136 |
werkzeug.datastructures.headers
|
__eq__
| null |
def __eq__(self, other):
def lowered(item):
return (item[0].lower(),) + item[1:]
return other.__class__ is self.__class__ and set(
map(lowered, other._list)
) == set(map(lowered, self._list))
|
(self, other)
|
42,137 |
werkzeug.datastructures.headers
|
__getitem__
| null |
def __getitem__(self, key, _get_mode=False):
if not _get_mode:
if isinstance(key, int):
return self._list[key]
elif isinstance(key, slice):
return self.__class__(self._list[key])
if not isinstance(key, str):
raise BadRequestKeyError(key)
ikey = key.lower()
for k, v in self._list:
if k.lower() == ikey:
return v
# micro optimization: if we are in get mode we will catch that
# exception one stack level down so we can raise a standard
# key error instead of our special one.
if _get_mode:
raise KeyError()
raise BadRequestKeyError(key)
|
(self, key, _get_mode=False)
|
42,138 |
werkzeug.datastructures.headers
|
__init__
| null |
def __init__(self, defaults=None):
self._list = []
if defaults is not None:
self.extend(defaults)
|
(self, defaults=None)
|
42,139 |
werkzeug.datastructures.headers
|
__iter__
|
Yield ``(key, value)`` tuples.
|
def __iter__(self):
"""Yield ``(key, value)`` tuples."""
return iter(self._list)
|
(self)
|
42,140 |
werkzeug.datastructures.headers
|
__len__
| null |
def __len__(self):
return len(self._list)
|
(self)
|
42,141 |
werkzeug.datastructures.headers
|
__repr__
| null |
def __repr__(self):
return f"{type(self).__name__}({list(self)!r})"
|
(self)
|
42,142 |
werkzeug.datastructures.headers
|
__setitem__
|
Like :meth:`set` but also supports index/slice based setting.
|
def __setitem__(self, key, value):
"""Like :meth:`set` but also supports index/slice based setting."""
if isinstance(key, (slice, int)):
if isinstance(key, int):
value = [value]
value = [(k, _str_header_value(v)) for (k, v) in value]
if isinstance(key, int):
self._list[key] = value[0]
else:
self._list[key] = value
else:
self.set(key, value)
|
(self, key, value)
|
42,143 |
werkzeug.datastructures.headers
|
__str__
|
Returns formatted headers suitable for HTTP transmission.
|
def __str__(self):
"""Returns formatted headers suitable for HTTP transmission."""
strs = []
for key, value in self.to_wsgi_list():
strs.append(f"{key}: {value}")
strs.append("\r\n")
return "\r\n".join(strs)
|
(self)
|
42,144 |
werkzeug.datastructures.headers
|
add
|
Add a new header tuple to the list.
Keyword arguments can specify additional parameters for the header
value, with underscores converted to dashes::
>>> d = Headers()
>>> d.add('Content-Type', 'text/plain')
>>> d.add('Content-Disposition', 'attachment', filename='foo.png')
The keyword argument dumping uses :func:`dump_options_header`
behind the scenes.
.. versionadded:: 0.4.1
keyword arguments were added for :mod:`wsgiref` compatibility.
|
def add(self, _key, _value, **kw):
"""Add a new header tuple to the list.
Keyword arguments can specify additional parameters for the header
value, with underscores converted to dashes::
>>> d = Headers()
>>> d.add('Content-Type', 'text/plain')
>>> d.add('Content-Disposition', 'attachment', filename='foo.png')
The keyword argument dumping uses :func:`dump_options_header`
behind the scenes.
.. versionadded:: 0.4.1
keyword arguments were added for :mod:`wsgiref` compatibility.
"""
if kw:
_value = _options_header_vkw(_value, kw)
_value = _str_header_value(_value)
self._list.append((_key, _value))
|
(self, _key, _value, **kw)
|
42,145 |
werkzeug.datastructures.headers
|
add_header
|
Add a new header tuple to the list.
An alias for :meth:`add` for compatibility with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.add_header` method.
|
def add_header(self, _key, _value, **_kw):
"""Add a new header tuple to the list.
An alias for :meth:`add` for compatibility with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.add_header` method.
"""
self.add(_key, _value, **_kw)
|
(self, _key, _value, **_kw)
|
42,146 |
werkzeug.datastructures.headers
|
clear
|
Clears all headers.
|
def clear(self):
"""Clears all headers."""
del self._list[:]
|
(self)
|
42,147 |
werkzeug.datastructures.headers
|
copy
| null |
def copy(self):
return self.__class__(self._list)
|
(self)
|
42,148 |
werkzeug.datastructures.headers
|
extend
|
Extend headers in this object with items from another object
containing header items as well as keyword arguments.
To replace existing keys instead of extending, use
:meth:`update` instead.
If provided, the first argument can be another :class:`Headers`
object, a :class:`MultiDict`, :class:`dict`, or iterable of
pairs.
.. versionchanged:: 1.0
Support :class:`MultiDict`. Allow passing ``kwargs``.
|
def extend(self, *args, **kwargs):
"""Extend headers in this object with items from another object
containing header items as well as keyword arguments.
To replace existing keys instead of extending, use
:meth:`update` instead.
If provided, the first argument can be another :class:`Headers`
object, a :class:`MultiDict`, :class:`dict`, or iterable of
pairs.
.. versionchanged:: 1.0
Support :class:`MultiDict`. Allow passing ``kwargs``.
"""
if len(args) > 1:
raise TypeError(f"update expected at most 1 arguments, got {len(args)}")
if args:
for key, value in iter_multi_items(args[0]):
self.add(key, value)
for key, value in iter_multi_items(kwargs):
self.add(key, value)
|
(self, *args, **kwargs)
|
42,149 |
werkzeug.datastructures.headers
|
get
|
Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the default as if the value was not
found:
>>> d = Headers([('Content-Length', '42')])
>>> d.get('Content-Length', type=int)
42
:param key: The key to be looked up.
:param default: The default value to be returned if the key can't
be looked up. If not further specified `None` is
returned.
:param type: A callable that is used to cast the value in the
:class:`Headers`. If a :exc:`ValueError` is raised
by this callable the default value is returned.
.. versionchanged:: 3.0
The ``as_bytes`` parameter was removed.
.. versionchanged:: 0.9
The ``as_bytes`` parameter was added.
|
def get(self, key, default=None, type=None):
"""Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the default as if the value was not
found:
>>> d = Headers([('Content-Length', '42')])
>>> d.get('Content-Length', type=int)
42
:param key: The key to be looked up.
:param default: The default value to be returned if the key can't
be looked up. If not further specified `None` is
returned.
:param type: A callable that is used to cast the value in the
:class:`Headers`. If a :exc:`ValueError` is raised
by this callable the default value is returned.
.. versionchanged:: 3.0
The ``as_bytes`` parameter was removed.
.. versionchanged:: 0.9
The ``as_bytes`` parameter was added.
"""
try:
rv = self.__getitem__(key, _get_mode=True)
except KeyError:
return default
if type is None:
return rv
try:
return type(rv)
except ValueError:
return default
|
(self, key, default=None, type=None)
|
42,150 |
werkzeug.datastructures.headers
|
get_all
|
Return a list of all the values for the named field.
This method is compatible with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.get_all` method.
|
def get_all(self, name):
"""Return a list of all the values for the named field.
This method is compatible with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.get_all` method.
"""
return self.getlist(name)
|
(self, name)
|
42,151 |
werkzeug.datastructures.headers
|
getlist
|
Return the list of items for a given key. If that key is not in the
:class:`Headers`, the return value will be an empty list. Just like
:meth:`get`, :meth:`getlist` accepts a `type` parameter. All items will
be converted with the callable defined there.
:param key: The key to be looked up.
:param type: A callable that is used to cast the value in the
:class:`Headers`. If a :exc:`ValueError` is raised
by this callable the value will be removed from the list.
:return: a :class:`list` of all the values for the key.
.. versionchanged:: 3.0
The ``as_bytes`` parameter was removed.
.. versionchanged:: 0.9
The ``as_bytes`` parameter was added.
|
def getlist(self, key, type=None):
"""Return the list of items for a given key. If that key is not in the
:class:`Headers`, the return value will be an empty list. Just like
:meth:`get`, :meth:`getlist` accepts a `type` parameter. All items will
be converted with the callable defined there.
:param key: The key to be looked up.
:param type: A callable that is used to cast the value in the
:class:`Headers`. If a :exc:`ValueError` is raised
by this callable the value will be removed from the list.
:return: a :class:`list` of all the values for the key.
.. versionchanged:: 3.0
The ``as_bytes`` parameter was removed.
.. versionchanged:: 0.9
The ``as_bytes`` parameter was added.
"""
ikey = key.lower()
result = []
for k, v in self:
if k.lower() == ikey:
if type is not None:
try:
v = type(v)
except ValueError:
continue
result.append(v)
return result
|
(self, key, type=None)
|
42,152 |
werkzeug.datastructures.headers
|
items
| null |
def items(self, lower=False):
for key, value in self:
if lower:
key = key.lower()
yield key, value
|
(self, lower=False)
|
42,153 |
werkzeug.datastructures.headers
|
keys
| null |
def keys(self, lower=False):
for key, _ in self.items(lower):
yield key
|
(self, lower=False)
|
42,154 |
werkzeug.datastructures.headers
|
pop
|
Removes and returns a key or index.
:param key: The key to be popped. If this is an integer the item at
that position is removed, if it's a string the value for
that key is. If the key is omitted or `None` the last
item is removed.
:return: an item.
|
def pop(self, key=None, default=_missing):
"""Removes and returns a key or index.
:param key: The key to be popped. If this is an integer the item at
that position is removed, if it's a string the value for
that key is. If the key is omitted or `None` the last
item is removed.
:return: an item.
"""
if key is None:
return self._list.pop()
if isinstance(key, int):
return self._list.pop(key)
try:
rv = self[key]
self.remove(key)
except KeyError:
if default is not _missing:
return default
raise
return rv
|
(self, key=None, default=no value)
|
42,155 |
werkzeug.datastructures.headers
|
popitem
|
Removes a key or index and returns a (key, value) item.
|
def popitem(self):
"""Removes a key or index and returns a (key, value) item."""
return self.pop()
|
(self)
|
42,156 |
werkzeug.datastructures.headers
|
remove
|
Remove a key.
:param key: The key to be removed.
|
def remove(self, key):
"""Remove a key.
:param key: The key to be removed.
"""
return self.__delitem__(key, _index_operation=False)
|
(self, key)
|
42,157 |
werkzeug.datastructures.headers
|
set
|
Remove all header tuples for `key` and add a new one. The newly
added key either appears at the end of the list if there was no
entry or replaces the first one.
Keyword arguments can specify additional parameters for the header
value, with underscores converted to dashes. See :meth:`add` for
more information.
.. versionchanged:: 0.6.1
:meth:`set` now accepts the same arguments as :meth:`add`.
:param key: The key to be inserted.
:param value: The value to be inserted.
|
def set(self, _key, _value, **kw):
"""Remove all header tuples for `key` and add a new one. The newly
added key either appears at the end of the list if there was no
entry or replaces the first one.
Keyword arguments can specify additional parameters for the header
value, with underscores converted to dashes. See :meth:`add` for
more information.
.. versionchanged:: 0.6.1
:meth:`set` now accepts the same arguments as :meth:`add`.
:param key: The key to be inserted.
:param value: The value to be inserted.
"""
if kw:
_value = _options_header_vkw(_value, kw)
_value = _str_header_value(_value)
if not self._list:
self._list.append((_key, _value))
return
listiter = iter(self._list)
ikey = _key.lower()
for idx, (old_key, _old_value) in enumerate(listiter):
if old_key.lower() == ikey:
# replace first occurrence
self._list[idx] = (_key, _value)
break
else:
self._list.append((_key, _value))
return
self._list[idx + 1 :] = [t for t in listiter if t[0].lower() != ikey]
|
(self, _key, _value, **kw)
|
42,158 |
werkzeug.datastructures.headers
|
setdefault
|
Return the first value for the key if it is in the headers,
otherwise set the header to the value given by ``default`` and
return that.
:param key: The header key to get.
:param default: The value to set for the key if it is not in the
headers.
|
def setdefault(self, key, default):
"""Return the first value for the key if it is in the headers,
otherwise set the header to the value given by ``default`` and
return that.
:param key: The header key to get.
:param default: The value to set for the key if it is not in the
headers.
"""
if key in self:
return self[key]
self.set(key, default)
return default
|
(self, key, default)
|
42,159 |
werkzeug.datastructures.headers
|
setlist
|
Remove any existing values for a header and add new ones.
:param key: The header key to set.
:param values: An iterable of values to set for the key.
.. versionadded:: 1.0
|
def setlist(self, key, values):
"""Remove any existing values for a header and add new ones.
:param key: The header key to set.
:param values: An iterable of values to set for the key.
.. versionadded:: 1.0
"""
if values:
values_iter = iter(values)
self.set(key, next(values_iter))
for value in values_iter:
self.add(key, value)
else:
self.remove(key)
|
(self, key, values)
|
42,160 |
werkzeug.datastructures.headers
|
setlistdefault
|
Return the list of values for the key if it is in the
headers, otherwise set the header to the list of values given
by ``default`` and return that.
Unlike :meth:`MultiDict.setlistdefault`, modifying the returned
list will not affect the headers.
:param key: The header key to get.
:param default: An iterable of values to set for the key if it
is not in the headers.
.. versionadded:: 1.0
|
def setlistdefault(self, key, default):
"""Return the list of values for the key if it is in the
headers, otherwise set the header to the list of values given
by ``default`` and return that.
Unlike :meth:`MultiDict.setlistdefault`, modifying the returned
list will not affect the headers.
:param key: The header key to get.
:param default: An iterable of values to set for the key if it
is not in the headers.
.. versionadded:: 1.0
"""
if key not in self:
self.setlist(key, default)
return self.getlist(key)
|
(self, key, default)
|
42,161 |
werkzeug.datastructures.headers
|
to_wsgi_list
|
Convert the headers into a list suitable for WSGI.
:return: list
|
def to_wsgi_list(self):
"""Convert the headers into a list suitable for WSGI.
:return: list
"""
return list(self)
|
(self)
|
42,162 |
werkzeug.datastructures.headers
|
update
|
Replace headers in this object with items from another
headers object and keyword arguments.
To extend existing keys instead of replacing, use :meth:`extend`
instead.
If provided, the first argument can be another :class:`Headers`
object, a :class:`MultiDict`, :class:`dict`, or iterable of
pairs.
.. versionadded:: 1.0
|
def update(self, *args, **kwargs):
"""Replace headers in this object with items from another
headers object and keyword arguments.
To extend existing keys instead of replacing, use :meth:`extend`
instead.
If provided, the first argument can be another :class:`Headers`
object, a :class:`MultiDict`, :class:`dict`, or iterable of
pairs.
.. versionadded:: 1.0
"""
if len(args) > 1:
raise TypeError(f"update expected at most 1 arguments, got {len(args)}")
if args:
mapping = args[0]
if isinstance(mapping, (Headers, MultiDict)):
for key in mapping.keys():
self.setlist(key, mapping.getlist(key))
elif isinstance(mapping, dict):
for key, value in mapping.items():
if isinstance(value, (list, tuple)):
self.setlist(key, value)
else:
self.set(key, value)
else:
for key, value in mapping:
self.set(key, value)
for key, value in kwargs.items():
if isinstance(value, (list, tuple)):
self.setlist(key, value)
else:
self.set(key, value)
|
(self, *args, **kwargs)
|
42,163 |
werkzeug.datastructures.headers
|
values
| null |
def values(self):
for _, value in self.items():
yield value
|
(self)
|
42,164 |
werkzeug.exceptions
|
InternalServerError
|
*500* `Internal Server Error`
Raise if an internal server error occurred. This is a good fallback if an
unknown error occurred in the dispatcher.
.. versionchanged:: 1.0.0
Added the :attr:`original_exception` attribute.
|
class InternalServerError(HTTPException):
"""*500* `Internal Server Error`
Raise if an internal server error occurred. This is a good fallback if an
unknown error occurred in the dispatcher.
.. versionchanged:: 1.0.0
Added the :attr:`original_exception` attribute.
"""
code = 500
description = (
"The server encountered an internal error and was unable to"
" complete your request. Either the server is overloaded or"
" there is an error in the application."
)
def __init__(
self,
description: str | None = None,
response: Response | None = None,
original_exception: BaseException | None = None,
) -> None:
#: The original exception that caused this 500 error. Can be
#: used by frameworks to provide context when handling
#: unexpected errors.
self.original_exception = original_exception
super().__init__(description=description, response=response)
|
(description: str | None = None, response: 'Response | None' = None, original_exception: 'BaseException | None' = None) -> 'None'
|
42,166 |
werkzeug.exceptions
|
__init__
| null |
def __init__(
self,
description: str | None = None,
response: Response | None = None,
original_exception: BaseException | None = None,
) -> None:
#: The original exception that caused this 500 error. Can be
#: used by frameworks to provide context when handling
#: unexpected errors.
self.original_exception = original_exception
super().__init__(description=description, response=response)
|
(self, description: 'str | None' = None, response: 'Response | None' = None, original_exception: 'BaseException | None' = None) -> 'None'
|
42,183 |
werkzeug.exceptions
|
MethodNotAllowed
|
*405* `Method Not Allowed`
Raise if the server used a method the resource does not handle. For
example `POST` if the resource is view only. Especially useful for REST.
The first argument for this exception should be a list of allowed methods.
Strictly speaking the response would be invalid if you don't provide valid
methods in the header which you can do with that list.
|
class MethodNotAllowed(HTTPException):
"""*405* `Method Not Allowed`
Raise if the server used a method the resource does not handle. For
example `POST` if the resource is view only. Especially useful for REST.
The first argument for this exception should be a list of allowed methods.
Strictly speaking the response would be invalid if you don't provide valid
methods in the header which you can do with that list.
"""
code = 405
description = "The method is not allowed for the requested URL."
def __init__(
self,
valid_methods: t.Iterable[str] | None = None,
description: str | None = None,
response: Response | None = None,
) -> None:
"""Takes an optional list of valid http methods
starting with werkzeug 0.3 the list will be mandatory."""
super().__init__(description=description, response=response)
self.valid_methods = valid_methods
def get_headers(
self,
environ: WSGIEnvironment | None = None,
scope: dict[str, t.Any] | None = None,
) -> list[tuple[str, str]]:
headers = super().get_headers(environ, scope)
if self.valid_methods:
headers.append(("Allow", ", ".join(self.valid_methods)))
return headers
|
(valid_methods: 't.Iterable[str] | None' = None, description: str | None = None, response: 'Response | None' = None) -> 'None'
|
42,185 |
werkzeug.exceptions
|
__init__
|
Takes an optional list of valid http methods
starting with werkzeug 0.3 the list will be mandatory.
|
def __init__(
self,
valid_methods: t.Iterable[str] | None = None,
description: str | None = None,
response: Response | None = None,
) -> None:
"""Takes an optional list of valid http methods
starting with werkzeug 0.3 the list will be mandatory."""
super().__init__(description=description, response=response)
self.valid_methods = valid_methods
|
(self, valid_methods: 't.Iterable[str] | None' = None, description: 'str | None' = None, response: 'Response | None' = None) -> 'None'
|
42,190 |
werkzeug.exceptions
|
get_headers
| null |
def get_headers(
self,
environ: WSGIEnvironment | None = None,
scope: dict[str, t.Any] | None = None,
) -> list[tuple[str, str]]:
headers = super().get_headers(environ, scope)
if self.valid_methods:
headers.append(("Allow", ", ".join(self.valid_methods)))
return headers
|
(self, environ: 'WSGIEnvironment | None' = None, scope: 'dict[str, t.Any] | None' = None) -> 'list[tuple[str, str]]'
|
42,192 |
builtins
|
method
|
method(function, instance)
Create a bound instance method object.
|
from builtins import method
| null |
42,193 |
flask.views
|
MethodView
|
Dispatches request methods to the corresponding instance methods.
For example, if you implement a ``get`` method, it will be used to
handle ``GET`` requests.
This can be useful for defining a REST API.
:attr:`methods` is automatically set based on the methods defined on
the class.
See :doc:`views` for a detailed guide.
.. code-block:: python
class CounterAPI(MethodView):
def get(self):
return str(session.get("counter", 0))
def post(self):
session["counter"] = session.get("counter", 0) + 1
return redirect(url_for("counter"))
app.add_url_rule(
"/counter", view_func=CounterAPI.as_view("counter")
)
|
class MethodView(View):
"""Dispatches request methods to the corresponding instance methods.
For example, if you implement a ``get`` method, it will be used to
handle ``GET`` requests.
This can be useful for defining a REST API.
:attr:`methods` is automatically set based on the methods defined on
the class.
See :doc:`views` for a detailed guide.
.. code-block:: python
class CounterAPI(MethodView):
def get(self):
return str(session.get("counter", 0))
def post(self):
session["counter"] = session.get("counter", 0) + 1
return redirect(url_for("counter"))
app.add_url_rule(
"/counter", view_func=CounterAPI.as_view("counter")
)
"""
def __init_subclass__(cls, **kwargs: t.Any) -> None:
super().__init_subclass__(**kwargs)
if "methods" not in cls.__dict__:
methods = set()
for base in cls.__bases__:
if getattr(base, "methods", None):
methods.update(base.methods) # type: ignore[attr-defined]
for key in http_method_funcs:
if hasattr(cls, key):
methods.add(key.upper())
if methods:
cls.methods = methods
def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:
meth = getattr(self, request.method.lower(), None)
# If the request method is HEAD and we don't have a handler for it
# retry with GET.
if meth is None and request.method == "HEAD":
meth = getattr(self, "get", None)
assert meth is not None, f"Unimplemented method {request.method!r}"
return current_app.ensure_sync(meth)(**kwargs) # type: ignore[no-any-return]
|
()
|
42,194 |
flask.views
|
dispatch_request
| null |
def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:
meth = getattr(self, request.method.lower(), None)
# If the request method is HEAD and we don't have a handler for it
# retry with GET.
if meth is None and request.method == "HEAD":
meth = getattr(self, "get", None)
assert meth is not None, f"Unimplemented method {request.method!r}"
return current_app.ensure_sync(meth)(**kwargs) # type: ignore[no-any-return]
|
(self, **kwargs: 't.Any') -> 'ft.ResponseReturnValue'
|
42,195 |
werkzeug.exceptions
|
NotAcceptable
|
*406* `Not Acceptable`
Raise if the server can't return any content conforming to the
`Accept` headers of the client.
|
class NotAcceptable(HTTPException):
"""*406* `Not Acceptable`
Raise if the server can't return any content conforming to the
`Accept` headers of the client.
"""
code = 406
description = (
"The resource identified by the request is only capable of"
" generating response entities which have content"
" characteristics not acceptable according to the accept"
" headers sent in the request."
)
|
(description: str | None = None, response: 'Response | None' = None) -> 'None'
|
42,204 |
werkzeug.exceptions
|
NotFound
|
*404* `Not Found`
Raise if a resource does not exist and never existed.
|
class NotFound(HTTPException):
"""*404* `Not Found`
Raise if a resource does not exist and never existed.
"""
code = 404
description = (
"The requested URL was not found on the server. If you entered"
" the URL manually please check your spelling and try again."
)
|
(description: str | None = None, response: 'Response | None' = None) -> 'None'
|
42,214 |
flask_restful
|
Resource
|
Represents an abstract RESTful resource. Concrete resources should
extend from this class and expose methods for each supported HTTP
method. If a resource is invoked with an unsupported HTTP method,
the API will return a response with status 405 Method Not Allowed.
Otherwise the appropriate method is called and passed all arguments
from the url rule used when adding the resource to an Api instance. See
:meth:`~flask_restful.Api.add_resource` for details.
|
class Resource(MethodView):
"""
Represents an abstract RESTful resource. Concrete resources should
extend from this class and expose methods for each supported HTTP
method. If a resource is invoked with an unsupported HTTP method,
the API will return a response with status 405 Method Not Allowed.
Otherwise the appropriate method is called and passed all arguments
from the url rule used when adding the resource to an Api instance. See
:meth:`~flask_restful.Api.add_resource` for details.
"""
representations = None
method_decorators = []
def dispatch_request(self, *args, **kwargs):
# Taken from flask
#noinspection PyUnresolvedReferences
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
if isinstance(self.method_decorators, Mapping):
decorators = self.method_decorators.get(request.method.lower(), [])
else:
decorators = self.method_decorators
for decorator in decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, ResponseBase): # There may be a better way to test
return resp
representations = self.representations or OrderedDict()
#noinspection PyUnresolvedReferences
mediatype = request.accept_mimetypes.best_match(representations, default=None)
if mediatype in representations:
data, code, headers = unpack(resp)
resp = representations[mediatype](data, code, headers)
resp.headers['Content-Type'] = mediatype
return resp
return resp
|
()
|
42,215 |
flask_restful
|
dispatch_request
| null |
def dispatch_request(self, *args, **kwargs):
# Taken from flask
#noinspection PyUnresolvedReferences
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
if isinstance(self.method_decorators, Mapping):
decorators = self.method_decorators.get(request.method.lower(), [])
else:
decorators = self.method_decorators
for decorator in decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, ResponseBase): # There may be a better way to test
return resp
representations = self.representations or OrderedDict()
#noinspection PyUnresolvedReferences
mediatype = request.accept_mimetypes.best_match(representations, default=None)
if mediatype in representations:
data, code, headers = unpack(resp)
resp = representations[mediatype](data, code, headers)
resp.headers['Content-Type'] = mediatype
return resp
return resp
|
(self, *args, **kwargs)
|
42,216 |
werkzeug.wrappers.response
|
Response
|
Represents an outgoing WSGI HTTP response with body, status, and
headers. Has properties and methods for using the functionality
defined by various HTTP specs.
The response body is flexible to support different use cases. The
simple form is passing bytes, or a string which will be encoded as
UTF-8. Passing an iterable of bytes or strings makes this a
streaming response. A generator is particularly useful for building
a CSV file in memory or using SSE (Server Sent Events). A file-like
object is also iterable, although the
:func:`~werkzeug.utils.send_file` helper should be used in that
case.
The response object is itself a WSGI application callable. When
called (:meth:`__call__`) with ``environ`` and ``start_response``,
it will pass its status and headers to ``start_response`` then
return its body as an iterable.
.. code-block:: python
from werkzeug.wrappers.response import Response
def index():
return Response("Hello, World!")
def application(environ, start_response):
path = environ.get("PATH_INFO") or "/"
if path == "/":
response = index()
else:
response = Response("Not Found", status=404)
return response(environ, start_response)
:param response: The data for the body of the response. A string or
bytes, or tuple or list of strings or bytes, for a fixed-length
response, or any other iterable of strings or bytes for a
streaming response. Defaults to an empty body.
:param status: The status code for the response. Either an int, in
which case the default status message is added, or a string in
the form ``{code} {message}``, like ``404 Not Found``. Defaults
to 200.
:param headers: A :class:`~werkzeug.datastructures.Headers` object,
or a list of ``(key, value)`` tuples that will be converted to a
``Headers`` object.
:param mimetype: The mime type (content type without charset or
other parameters) of the response. If the value starts with
``text/`` (or matches some other special cases), the charset
will be added to create the ``content_type``.
:param content_type: The full content type of the response.
Overrides building the value from ``mimetype``.
:param direct_passthrough: Pass the response body directly through
as the WSGI iterable. This can be used when the body is a binary
file or other iterator of bytes, to skip some unnecessary
checks. Use :func:`~werkzeug.utils.send_file` instead of setting
this manually.
.. versionchanged:: 2.1
Old ``BaseResponse`` and mixin classes were removed.
.. versionchanged:: 2.0
Combine ``BaseResponse`` and mixins into a single ``Response``
class.
.. versionchanged:: 0.5
The ``direct_passthrough`` parameter was added.
|
class Response(_SansIOResponse):
"""Represents an outgoing WSGI HTTP response with body, status, and
headers. Has properties and methods for using the functionality
defined by various HTTP specs.
The response body is flexible to support different use cases. The
simple form is passing bytes, or a string which will be encoded as
UTF-8. Passing an iterable of bytes or strings makes this a
streaming response. A generator is particularly useful for building
a CSV file in memory or using SSE (Server Sent Events). A file-like
object is also iterable, although the
:func:`~werkzeug.utils.send_file` helper should be used in that
case.
The response object is itself a WSGI application callable. When
called (:meth:`__call__`) with ``environ`` and ``start_response``,
it will pass its status and headers to ``start_response`` then
return its body as an iterable.
.. code-block:: python
from werkzeug.wrappers.response import Response
def index():
return Response("Hello, World!")
def application(environ, start_response):
path = environ.get("PATH_INFO") or "/"
if path == "/":
response = index()
else:
response = Response("Not Found", status=404)
return response(environ, start_response)
:param response: The data for the body of the response. A string or
bytes, or tuple or list of strings or bytes, for a fixed-length
response, or any other iterable of strings or bytes for a
streaming response. Defaults to an empty body.
:param status: The status code for the response. Either an int, in
which case the default status message is added, or a string in
the form ``{code} {message}``, like ``404 Not Found``. Defaults
to 200.
:param headers: A :class:`~werkzeug.datastructures.Headers` object,
or a list of ``(key, value)`` tuples that will be converted to a
``Headers`` object.
:param mimetype: The mime type (content type without charset or
other parameters) of the response. If the value starts with
``text/`` (or matches some other special cases), the charset
will be added to create the ``content_type``.
:param content_type: The full content type of the response.
Overrides building the value from ``mimetype``.
:param direct_passthrough: Pass the response body directly through
as the WSGI iterable. This can be used when the body is a binary
file or other iterator of bytes, to skip some unnecessary
checks. Use :func:`~werkzeug.utils.send_file` instead of setting
this manually.
.. versionchanged:: 2.1
Old ``BaseResponse`` and mixin classes were removed.
.. versionchanged:: 2.0
Combine ``BaseResponse`` and mixins into a single ``Response``
class.
.. versionchanged:: 0.5
The ``direct_passthrough`` parameter was added.
"""
#: if set to `False` accessing properties on the response object will
#: not try to consume the response iterator and convert it into a list.
#:
#: .. versionadded:: 0.6.2
#:
#: That attribute was previously called `implicit_seqence_conversion`.
#: (Notice the typo). If you did use this feature, you have to adapt
#: your code to the name change.
implicit_sequence_conversion = True
#: If a redirect ``Location`` header is a relative URL, make it an
#: absolute URL, including scheme and domain.
#:
#: .. versionchanged:: 2.1
#: This is disabled by default, so responses will send relative
#: redirects.
#:
#: .. versionadded:: 0.8
autocorrect_location_header = False
#: Should this response object automatically set the content-length
#: header if possible? This is true by default.
#:
#: .. versionadded:: 0.8
automatically_set_content_length = True
#: The response body to send as the WSGI iterable. A list of strings
#: or bytes represents a fixed-length response, any other iterable
#: is a streaming response. Strings are encoded to bytes as UTF-8.
#:
#: Do not set to a plain string or bytes, that will cause sending
#: the response to be very inefficient as it will iterate one byte
#: at a time.
response: t.Iterable[str] | t.Iterable[bytes]
def __init__(
self,
response: t.Iterable[bytes] | bytes | t.Iterable[str] | str | None = None,
status: int | str | HTTPStatus | None = None,
headers: t.Mapping[str, str | t.Iterable[str]]
| t.Iterable[tuple[str, str]]
| None = None,
mimetype: str | None = None,
content_type: str | None = None,
direct_passthrough: bool = False,
) -> None:
super().__init__(
status=status,
headers=headers,
mimetype=mimetype,
content_type=content_type,
)
#: Pass the response body directly through as the WSGI iterable.
#: This can be used when the body is a binary file or other
#: iterator of bytes, to skip some unnecessary checks. Use
#: :func:`~werkzeug.utils.send_file` instead of setting this
#: manually.
self.direct_passthrough = direct_passthrough
self._on_close: list[t.Callable[[], t.Any]] = []
# we set the response after the headers so that if a class changes
# the charset attribute, the data is set in the correct charset.
if response is None:
self.response = []
elif isinstance(response, (str, bytes, bytearray)):
self.set_data(response)
else:
self.response = response
def call_on_close(self, func: t.Callable[[], t.Any]) -> t.Callable[[], t.Any]:
"""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
"""
self._on_close.append(func)
return func
def __repr__(self) -> str:
if self.is_sequence:
body_info = f"{sum(map(len, self.iter_encoded()))} bytes"
else:
body_info = "streamed" if self.is_streamed else "likely-streamed"
return f"<{type(self).__name__} {body_info} [{self.status}]>"
@classmethod
def force_type(
cls, response: Response, environ: WSGIEnvironment | None = None
) -> Response:
"""Enforce that the WSGI response is a response object of the current
type. Werkzeug will use the :class:`Response` internally in many
situations like the exceptions. If you call :meth:`get_response` on an
exception you will get back a regular :class:`Response` object, even
if you are using a custom subclass.
This method can enforce a given response type, and it will also
convert arbitrary WSGI callables into response objects if an environ
is provided::
# convert a Werkzeug response object into an instance of the
# MyResponseClass subclass.
response = MyResponseClass.force_type(response)
# convert any WSGI application into a response object
response = MyResponseClass.force_type(response, environ)
This is especially useful if you want to post-process responses in
the main dispatcher and use functionality provided by your subclass.
Keep in mind that this will modify response objects in place if
possible!
:param response: a response object or wsgi application.
:param environ: a WSGI environment object.
:return: a response object.
"""
if not isinstance(response, Response):
if environ is None:
raise TypeError(
"cannot convert WSGI application into response"
" objects without an environ"
)
from ..test import run_wsgi_app
response = Response(*run_wsgi_app(response, environ))
response.__class__ = cls
return response
@classmethod
def from_app(
cls, app: WSGIApplication, environ: WSGIEnvironment, buffered: bool = False
) -> Response:
"""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.
"""
from ..test import run_wsgi_app
return cls(*run_wsgi_app(app, environ, buffered))
@t.overload
def get_data(self, as_text: t.Literal[False] = False) -> bytes: ...
@t.overload
def get_data(self, as_text: t.Literal[True]) -> str: ...
def get_data(self, as_text: bool = False) -> bytes | str:
"""The string representation of the response body. Whenever you call
this property the response iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
:attr:`implicit_sequence_conversion` to `False`.
If `as_text` is set to `True` the return value will be a decoded
string.
.. versionadded:: 0.9
"""
self._ensure_sequence()
rv = b"".join(self.iter_encoded())
if as_text:
return rv.decode()
return rv
def set_data(self, value: bytes | str) -> None:
"""Sets a new string as response. The value must be a string or
bytes. If a string is set it's encoded to the charset of the
response (utf-8 by default).
.. versionadded:: 0.9
"""
if isinstance(value, str):
value = value.encode()
self.response = [value]
if self.automatically_set_content_length:
self.headers["Content-Length"] = str(len(value))
data = property(
get_data,
set_data,
doc="A descriptor that calls :meth:`get_data` and :meth:`set_data`.",
)
def calculate_content_length(self) -> int | None:
"""Returns the content length if available or `None` otherwise."""
try:
self._ensure_sequence()
except RuntimeError:
return None
return sum(len(x) for x in self.iter_encoded())
def _ensure_sequence(self, mutable: bool = False) -> None:
"""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
"""
if self.is_sequence:
# if we need a mutable object, we ensure it's a list.
if mutable and not isinstance(self.response, list):
self.response = list(self.response) # type: ignore
return
if self.direct_passthrough:
raise RuntimeError(
"Attempted implicit sequence conversion but the"
" response object is in direct passthrough mode."
)
if not self.implicit_sequence_conversion:
raise RuntimeError(
"The response object required the iterable to be a"
" sequence, but the implicit conversion was disabled."
" Call make_sequence() yourself."
)
self.make_sequence()
def make_sequence(self) -> None:
"""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
"""
if not self.is_sequence:
# if we consume an iterable we have to ensure that the close
# method of the iterable is called if available when we tear
# down the response
close = getattr(self.response, "close", None)
self.response = list(self.iter_encoded())
if close is not None:
self.call_on_close(close)
def iter_encoded(self) -> t.Iterator[bytes]:
"""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.
"""
# Encode in a separate function so that self.response is fetched
# early. This allows us to wrap the response with the return
# value from get_app_iter or iter_encoded.
return _iter_encoded(self.response)
@property
def is_streamed(self) -> bool:
"""If the response is streamed (the response is not an iterable with
a length information) this property is `True`. In this case streamed
means that there is no information about the number of iterations.
This is usually `True` if a generator is passed to the response object.
This is useful for checking before applying some sort of post
filtering that should not take place for streamed responses.
"""
try:
len(self.response) # type: ignore
except (TypeError, AttributeError):
return True
return False
@property
def is_sequence(self) -> bool:
"""If the iterator is buffered, this property will be `True`. A
response object will consider an iterator to be buffered if the
response attribute is a list or tuple.
.. versionadded:: 0.6
"""
return isinstance(self.response, (tuple, list))
def close(self) -> None:
"""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.
"""
if hasattr(self.response, "close"):
self.response.close()
for func in self._on_close:
func()
def __enter__(self) -> Response:
return self
def __exit__(self, exc_type, exc_value, tb): # type: ignore
self.close()
def freeze(self) -> None:
"""Make the response object ready to be pickled. Does the
following:
* Buffer the response into a list, ignoring
:attr:`implicity_sequence_conversion` and
:attr:`direct_passthrough`.
* Set the ``Content-Length`` header.
* Generate an ``ETag`` header if one is not already set.
.. versionchanged:: 2.1
Removed the ``no_etag`` parameter.
.. versionchanged:: 2.0
An ``ETag`` header is always added.
.. versionchanged:: 0.6
The ``Content-Length`` header is set.
"""
# Always freeze the encoded response body, ignore
# implicit_sequence_conversion and direct_passthrough.
self.response = list(self.iter_encoded())
self.headers["Content-Length"] = str(sum(map(len, self.response)))
self.add_etag()
def get_wsgi_headers(self, environ: WSGIEnvironment) -> Headers:
"""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.
"""
headers = Headers(self.headers)
location: str | None = None
content_location: str | None = None
content_length: str | int | None = None
status = self.status_code
# iterate over the headers to find all values in one go. Because
# get_wsgi_headers is used each response that gives us a tiny
# speedup.
for key, value in headers:
ikey = key.lower()
if ikey == "location":
location = value
elif ikey == "content-location":
content_location = value
elif ikey == "content-length":
content_length = value
if location is not None:
location = iri_to_uri(location)
if self.autocorrect_location_header:
# Make the location header an absolute URL.
current_url = get_current_url(environ, strip_querystring=True)
current_url = iri_to_uri(current_url)
location = urljoin(current_url, location)
headers["Location"] = location
# make sure the content location is a URL
if content_location is not None:
headers["Content-Location"] = iri_to_uri(content_location)
if 100 <= status < 200 or status == 204:
# Per section 3.3.2 of RFC 7230, "a server MUST NOT send a
# Content-Length header field in any response with a status
# code of 1xx (Informational) or 204 (No Content)."
headers.remove("Content-Length")
elif status == 304:
remove_entity_headers(headers)
# if we can determine the content length automatically, we
# should try to do that. But only if this does not involve
# flattening the iterator or encoding of strings in the
# response. We however should not do that if we have a 304
# response.
if (
self.automatically_set_content_length
and self.is_sequence
and content_length is None
and status not in (204, 304)
and not (100 <= status < 200)
):
content_length = sum(len(x) for x in self.iter_encoded())
headers["Content-Length"] = str(content_length)
return headers
def get_app_iter(self, environ: WSGIEnvironment) -> t.Iterable[bytes]:
"""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.
"""
status = self.status_code
if (
environ["REQUEST_METHOD"] == "HEAD"
or 100 <= status < 200
or status in (204, 304)
):
iterable: t.Iterable[bytes] = ()
elif self.direct_passthrough:
return self.response # type: ignore
else:
iterable = self.iter_encoded()
return ClosingIterator(iterable, self.close)
def get_wsgi_response(
self, environ: WSGIEnvironment
) -> tuple[t.Iterable[bytes], str, list[tuple[str, str]]]:
"""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.
"""
headers = self.get_wsgi_headers(environ)
app_iter = self.get_app_iter(environ)
return app_iter, self.status, headers.to_wsgi_list()
def __call__(
self, environ: WSGIEnvironment, start_response: StartResponse
) -> t.Iterable[bytes]:
"""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
"""
app_iter, status, headers = self.get_wsgi_response(environ)
start_response(status, headers)
return app_iter
# JSON
#: A module or other object that has ``dumps`` and ``loads``
#: functions that match the API of the built-in :mod:`json` module.
json_module = json
@property
def json(self) -> t.Any | None:
"""The parsed JSON data if :attr:`mimetype` indicates JSON
(:mimetype:`application/json`, see :attr:`is_json`).
Calls :meth:`get_json` with default arguments.
"""
return self.get_json()
@t.overload
def get_json(self, force: bool = ..., silent: t.Literal[False] = ...) -> t.Any: ...
@t.overload
def get_json(self, force: bool = ..., silent: bool = ...) -> t.Any | None: ...
def get_json(self, force: bool = False, silent: bool = False) -> t.Any | None:
"""Parse :attr:`data` as JSON. Useful during testing.
If the mimetype does not indicate JSON
(:mimetype:`application/json`, see :attr:`is_json`), this
returns ``None``.
Unlike :meth:`Request.get_json`, the result is not cached.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
"""
if not (force or self.is_json):
return None
data = self.get_data()
try:
return self.json_module.loads(data)
except ValueError:
if not silent:
raise
return None
# Stream
@cached_property
def stream(self) -> ResponseStream:
"""The response iterable as write-only stream."""
return ResponseStream(self)
def _wrap_range_response(self, start: int, length: int) -> None:
"""Wrap existing Response in case of Range Request context."""
if self.status_code == 206:
self.response = _RangeWrapper(self.response, start, length) # type: ignore
def _is_range_request_processable(self, environ: WSGIEnvironment) -> bool:
"""Return ``True`` if `Range` header is present and if underlying
resource is considered unchanged when compared with `If-Range` header.
"""
return (
"HTTP_IF_RANGE" not in environ
or not is_resource_modified(
environ,
self.headers.get("etag"),
None,
self.headers.get("last-modified"),
ignore_if_range=False,
)
) and "HTTP_RANGE" in environ
def _process_range_request(
self,
environ: WSGIEnvironment,
complete_length: int | None,
accept_ranges: bool | str,
) -> bool:
"""Handle Range Request related headers (RFC7233). If `Accept-Ranges`
header is valid, and Range Request is processable, we set the headers
as described by the RFC, and wrap the underlying response in a
RangeWrapper.
Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise.
:raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
if `Range` header could not be parsed or satisfied.
.. versionchanged:: 2.0
Returns ``False`` if the length is 0.
"""
from ..exceptions import RequestedRangeNotSatisfiable
if (
not accept_ranges
or complete_length is None
or complete_length == 0
or not self._is_range_request_processable(environ)
):
return False
if accept_ranges is True:
accept_ranges = "bytes"
parsed_range = parse_range_header(environ.get("HTTP_RANGE"))
if parsed_range is None:
raise RequestedRangeNotSatisfiable(complete_length)
range_tuple = parsed_range.range_for_length(complete_length)
content_range_header = parsed_range.to_content_range_header(complete_length)
if range_tuple is None or content_range_header is None:
raise RequestedRangeNotSatisfiable(complete_length)
content_length = range_tuple[1] - range_tuple[0]
self.headers["Content-Length"] = str(content_length)
self.headers["Accept-Ranges"] = accept_ranges
self.content_range = content_range_header # type: ignore
self.status_code = 206
self._wrap_range_response(range_tuple[0], content_length)
return True
def make_conditional(
self,
request_or_environ: WSGIEnvironment | Request,
accept_ranges: bool | str = False,
complete_length: int | None = None,
) -> Response:
"""Make the response conditional to the request. This method works
best if an etag was defined for the response already. The `add_etag`
method can be used to do that. If called without etag just the date
header is set.
This does nothing if the request method in the request or environ is
anything but GET or HEAD.
For optimal performance when handling range requests, it's recommended
that your response data object implements `seekable`, `seek` and `tell`
methods as described by :py:class:`io.IOBase`. Objects returned by
:meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.
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.
:param accept_ranges: This parameter dictates the value of
`Accept-Ranges` header. If ``False`` (default),
the header is not set. If ``True``, it will be set
to ``"bytes"``. If it's a string, it will use this
value.
:param complete_length: Will be used only in valid Range Requests.
It will set `Content-Range` complete length
value and compute `Content-Length` real value.
This parameter is mandatory for successful
Range Requests completion.
:raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
if `Range` header could not be parsed or satisfied.
.. versionchanged:: 2.0
Range processing is skipped if length is 0 instead of
raising a 416 Range Not Satisfiable error.
"""
environ = _get_environ(request_or_environ)
if environ["REQUEST_METHOD"] in ("GET", "HEAD"):
# if the date is not in the headers, add it now. We however
# will not override an already existing header. Unfortunately
# this header will be overridden by many WSGI servers including
# wsgiref.
if "date" not in self.headers:
self.headers["Date"] = http_date()
is206 = self._process_range_request(environ, complete_length, accept_ranges)
if not is206 and not is_resource_modified(
environ,
self.headers.get("etag"),
None,
self.headers.get("last-modified"),
):
if parse_etags(environ.get("HTTP_IF_MATCH")):
self.status_code = 412
else:
self.status_code = 304
if (
self.automatically_set_content_length
and "content-length" not in self.headers
):
length = self.calculate_content_length()
if length is not None:
self.headers["Content-Length"] = str(length)
return self
def add_etag(self, overwrite: bool = False, weak: bool = False) -> None:
"""Add an etag for the current response if there is none yet.
.. versionchanged:: 2.0
SHA-1 is used to generate the value. MD5 may not be
available in some environments.
"""
if overwrite or "etag" not in self.headers:
self.set_etag(generate_etag(self.get_data()), weak)
|
(response: Union[Iterable[str], Iterable[bytes]] = None, status: 'int | str | HTTPStatus | None' = None, headers: werkzeug.datastructures.headers.Headers = None, mimetype: 'str | None' = None, content_type: 'str | None' = None, direct_passthrough: 'bool' = False) -> 'None'
|
42,245 |
flask_restful
|
_get_propagate_exceptions_bool
|
Handle Flask's propagate_exceptions.
If propagate_exceptions is set to True then the exceptions are re-raised rather than being handled
by the app’s error handlers.
The default value for Flask's app.config['PROPAGATE_EXCEPTIONS'] is None. In this case return a sensible
value: self.testing or self.debug.
|
def _get_propagate_exceptions_bool(app):
"""Handle Flask's propagate_exceptions.
If propagate_exceptions is set to True then the exceptions are re-raised rather than being handled
by the app’s error handlers.
The default value for Flask's app.config['PROPAGATE_EXCEPTIONS'] is None. In this case return a sensible
value: self.testing or self.debug.
"""
propagate_exceptions = app.config.get(_PROPAGATE_EXCEPTIONS, False)
if propagate_exceptions is None:
return app.testing or app.debug
return propagate_exceptions
|
(app)
|
42,246 |
flask_restful
|
_handle_flask_propagate_exceptions_config
| null |
def _handle_flask_propagate_exceptions_config(app, e):
propagate_exceptions = _get_propagate_exceptions_bool(app)
if not isinstance(e, HTTPException) and propagate_exceptions:
exc_type, exc_value, tb = sys.exc_info()
if exc_value is e:
raise
else:
raise e
|
(app, e)
|
42,247 |
flask_restful
|
abort
|
Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
|
def abort(http_status_code, **kwargs):
"""Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
"""
# noinspection PyUnresolvedReferences
try:
original_flask_abort(http_status_code)
except HTTPException as e:
if len(kwargs):
e.data = kwargs
raise
|
(http_status_code, **kwargs)
|
42,248 |
flask_restful.utils
|
http_status_message
|
Maps an HTTP status code to the textual status
|
def http_status_message(code):
"""Maps an HTTP status code to the textual status"""
return HTTP_STATUS_CODES.get(code, '')
|
(code)
|
42,249 |
flask_restful
|
marshal
|
Takes raw data (in the form of a dict, list, object) and a dict of
fields to output and filters the data based on those fields.
:param data: the actual object(s) from which the fields are taken from
:param fields: a dict of whose keys will make up the final serialized
response output
:param envelope: optional key that will be used to envelop the serialized
response
>>> from flask_restful import fields, marshal
>>> data = { 'a': 100, 'b': 'foo' }
>>> mfields = { 'a': fields.Raw }
>>> marshal(data, mfields)
OrderedDict([('a', 100)])
>>> marshal(data, mfields, envelope='data')
OrderedDict([('data', OrderedDict([('a', 100)]))])
|
def marshal(data, fields, envelope=None):
"""Takes raw data (in the form of a dict, list, object) and a dict of
fields to output and filters the data based on those fields.
:param data: the actual object(s) from which the fields are taken from
:param fields: a dict of whose keys will make up the final serialized
response output
:param envelope: optional key that will be used to envelop the serialized
response
>>> from flask_restful import fields, marshal
>>> data = { 'a': 100, 'b': 'foo' }
>>> mfields = { 'a': fields.Raw }
>>> marshal(data, mfields)
OrderedDict([('a', 100)])
>>> marshal(data, mfields, envelope='data')
OrderedDict([('data', OrderedDict([('a', 100)]))])
"""
def make(cls):
if isinstance(cls, type):
return cls()
return cls
if isinstance(data, (list, tuple)):
return (OrderedDict([(envelope, [marshal(d, fields) for d in data])])
if envelope else [marshal(d, fields) for d in data])
items = ((k, marshal(data, v) if isinstance(v, dict)
else make(v).output(k, data))
for k, v in fields.items())
return OrderedDict([(envelope, OrderedDict(items))]) if envelope else OrderedDict(items)
|
(data, fields, envelope=None)
|
42,250 |
flask_restful
|
marshal_with
|
A decorator that apply marshalling to the return values of your methods.
>>> from flask_restful import fields, marshal_with
>>> mfields = { 'a': fields.Raw }
>>> @marshal_with(mfields)
... def get():
... return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('a', 100)])
>>> @marshal_with(mfields, envelope='data')
... def get():
... return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('data', OrderedDict([('a', 100)]))])
see :meth:`flask_restful.marshal`
|
class marshal_with(object):
"""A decorator that apply marshalling to the return values of your methods.
>>> from flask_restful import fields, marshal_with
>>> mfields = { 'a': fields.Raw }
>>> @marshal_with(mfields)
... def get():
... return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('a', 100)])
>>> @marshal_with(mfields, envelope='data')
... def get():
... return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('data', OrderedDict([('a', 100)]))])
see :meth:`flask_restful.marshal`
"""
def __init__(self, fields, envelope=None):
"""
:param fields: a dict of whose keys will make up the final
serialized response output
:param envelope: optional key that will be used to envelop the serialized
response
"""
self.fields = fields
self.envelope = envelope
def __call__(self, f):
@wraps(f)
def wrapper(*args, **kwargs):
resp = f(*args, **kwargs)
if isinstance(resp, tuple):
data, code, headers = unpack(resp)
return marshal(data, self.fields, self.envelope), code, headers
else:
return marshal(resp, self.fields, self.envelope)
return wrapper
|
(fields, envelope=None)
|
42,251 |
flask_restful
|
__call__
| null |
def __call__(self, f):
@wraps(f)
def wrapper(*args, **kwargs):
resp = f(*args, **kwargs)
if isinstance(resp, tuple):
data, code, headers = unpack(resp)
return marshal(data, self.fields, self.envelope), code, headers
else:
return marshal(resp, self.fields, self.envelope)
return wrapper
|
(self, f)
|
42,252 |
flask_restful
|
__init__
|
:param fields: a dict of whose keys will make up the final
serialized response output
:param envelope: optional key that will be used to envelop the serialized
response
|
def __init__(self, fields, envelope=None):
"""
:param fields: a dict of whose keys will make up the final
serialized response output
:param envelope: optional key that will be used to envelop the serialized
response
"""
self.fields = fields
self.envelope = envelope
|
(self, fields, envelope=None)
|
42,253 |
flask_restful
|
marshal_with_field
|
A decorator that formats the return values of your methods with a single field.
>>> from flask_restful import marshal_with_field, fields
>>> @marshal_with_field(fields.List(fields.Integer))
... def get():
... return ['1', 2, 3.0]
...
>>> get()
[1, 2, 3]
see :meth:`flask_restful.marshal_with`
|
class marshal_with_field(object):
"""
A decorator that formats the return values of your methods with a single field.
>>> from flask_restful import marshal_with_field, fields
>>> @marshal_with_field(fields.List(fields.Integer))
... def get():
... return ['1', 2, 3.0]
...
>>> get()
[1, 2, 3]
see :meth:`flask_restful.marshal_with`
"""
def __init__(self, field):
"""
:param field: a single field with which to marshal the output.
"""
if isinstance(field, type):
self.field = field()
else:
self.field = field
def __call__(self, f):
@wraps(f)
def wrapper(*args, **kwargs):
resp = f(*args, **kwargs)
if isinstance(resp, tuple):
data, code, headers = unpack(resp)
return self.field.format(data), code, headers
return self.field.format(resp)
return wrapper
|
(field)
|
42,254 |
flask_restful
|
__call__
| null |
def __call__(self, f):
@wraps(f)
def wrapper(*args, **kwargs):
resp = f(*args, **kwargs)
if isinstance(resp, tuple):
data, code, headers = unpack(resp)
return self.field.format(data), code, headers
return self.field.format(resp)
return wrapper
|
(self, f)
|
42,255 |
flask_restful
|
__init__
|
:param field: a single field with which to marshal the output.
|
def __init__(self, field):
"""
:param field: a single field with which to marshal the output.
"""
if isinstance(field, type):
self.field = field()
else:
self.field = field
|
(self, field)
|
42,258 |
flask.helpers
|
make_response
|
Sometimes it is necessary to set additional headers in a view. Because
views do not have to return response objects but can return a value that
is converted into a response object by Flask itself, it becomes tricky to
add headers to it. This function can be called instead of using a return
and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header::
def index():
return render_template('index.html', foo=42)
You can now do something like this::
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
This function accepts the very same arguments you can return from a
view function. This for example creates a response with a 404 error
code::
response = make_response(render_template('not_found.html'), 404)
The other use case of this function is to force the return value of a
view function into a response which is helpful with view
decorators::
response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'
Internally this function does the following things:
- if no arguments are passed, it creates a new response argument
- if one argument is passed, :meth:`flask.Flask.make_response`
is invoked with it.
- if more than one argument is passed, the arguments are passed
to the :meth:`flask.Flask.make_response` function as tuple.
.. versionadded:: 0.6
|
def make_response(*args: t.Any) -> Response:
"""Sometimes it is necessary to set additional headers in a view. Because
views do not have to return response objects but can return a value that
is converted into a response object by Flask itself, it becomes tricky to
add headers to it. This function can be called instead of using a return
and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header::
def index():
return render_template('index.html', foo=42)
You can now do something like this::
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
This function accepts the very same arguments you can return from a
view function. This for example creates a response with a 404 error
code::
response = make_response(render_template('not_found.html'), 404)
The other use case of this function is to force the return value of a
view function into a response which is helpful with view
decorators::
response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'
Internally this function does the following things:
- if no arguments are passed, it creates a new response argument
- if one argument is passed, :meth:`flask.Flask.make_response`
is invoked with it.
- if more than one argument is passed, the arguments are passed
to the :meth:`flask.Flask.make_response` function as tuple.
.. versionadded:: 0.6
"""
if not args:
return current_app.response_class()
if len(args) == 1:
args = args[0]
return current_app.make_response(args)
|
(*args: 't.Any') -> 'Response'
|
42,259 |
flask_restful.representations.json
|
output_json
|
Makes a Flask response with a JSON encoded body
|
def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
settings = current_app.config.get('RESTFUL_JSON', {})
# If we're in debug mode, and the indent is not set, we set it to a
# reasonable value here. Note that this won't override any existing value
# that was set. We also set the "sort_keys" value.
if current_app.debug:
settings.setdefault('indent', 4)
settings.setdefault('sort_keys', not PY3)
# always end the json dumps with a new line
# see https://github.com/mitsuhiko/flask/pull/1262
dumped = dumps(data, **settings) + "\n"
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
|
(data, code, headers=None)
|
42,263 |
flask_restful.utils
|
unpack
|
Return a three tuple of data, code, and headers
|
def unpack(value):
"""Return a three tuple of data, code, and headers"""
if not isinstance(value, tuple):
return value, 200, {}
try:
data, code, headers = value
return data, code, headers
except ValueError:
pass
try:
data, code = value
return data, code, {}
except ValueError:
pass
return value, 200, {}
|
(value)
|
42,267 |
pydle.client
|
AlreadyInChannel
| null |
class AlreadyInChannel(Error):
def __init__(self, channel):
super().__init__('Already in channel: {}'.format(channel))
self.channel = channel
|
(channel)
|
42,268 |
pydle.client
|
__init__
| null |
def __init__(self, channel):
super().__init__('Already in channel: {}'.format(channel))
self.channel = channel
|
(self, channel)
|
42,269 |
pydle.client
|
BasicClient
|
Base IRC client class.
This class on its own is not complete: in order to be able to run properly, _has_message, _parse_message and _create_message have to be overloaded.
|
class BasicClient:
"""
Base IRC client class.
This class on its own is not complete: in order to be able to run properly, _has_message, _parse_message and _create_message have to be overloaded.
"""
READ_TIMEOUT = 300
RECONNECT_ON_ERROR = True
RECONNECT_MAX_ATTEMPTS = 3
RECONNECT_DELAYED = True
RECONNECT_DELAYS = [5, 5, 10, 30, 120, 600]
@property
def PING_TIMEOUT(self):
warnings.warn(
"PING_TIMEOUT has been moved to READ_TIMEOUT and may be removed in a future version. "
"Please migrate to READ_TIMEOUT.",
DeprecationWarning
)
return self.READ_TIMEOUT
@PING_TIMEOUT.setter
def PING_TIMEOUT(self, value):
warnings.warn(
"PING_TIMEOUT has been moved to READ_TIMEOUT and may be removed in a future version",
DeprecationWarning
)
self.READ_TIMEOUT = value
def __init__(self, nickname, fallback_nicknames=None, username=None, realname=None,
eventloop=None, **kwargs):
""" Create a client. """
self._nicknames = [nickname] + (fallback_nicknames or [])
self.username = username or nickname.lower()
self.realname = realname or nickname
if eventloop:
self.eventloop = eventloop
else:
self.eventloop = get_event_loop()
self.own_eventloop = not eventloop
self._reset_connection_attributes()
self._reset_attributes()
if kwargs:
self.logger.warning('Unused arguments: %s', ', '.join(kwargs.keys()))
def _reset_attributes(self):
""" Reset attributes. """
# Record-keeping.
self.channels = {}
self.users = {}
# Low-level data stuff.
self._receive_buffer = b''
self._pending = {}
self._handler_top_level = False
# Misc.
self.logger = logging.getLogger(__name__)
# Public connection attributes.
self.nickname = DEFAULT_NICKNAME
self.network = None
def _reset_connection_attributes(self):
""" Reset connection attributes. """
self.connection = None
self.encoding = None
self._autojoin_channels = []
self._reconnect_attempts = 0
## Connection.
def run(self, *args, **kwargs):
""" Connect and run bot in event loop. """
self.eventloop.run_until_complete(self.connect(*args, **kwargs))
try:
self.eventloop.run_forever()
finally:
self.eventloop.stop()
async def connect(self, hostname=None, port=None, reconnect=False, **kwargs):
""" Connect to IRC server. """
if (not hostname or not port) and not reconnect:
raise ValueError('Have to specify hostname and port if not reconnecting.')
# Disconnect from current connection.
if self.connected:
await self.disconnect(expected=True)
# Reset attributes and connect.
if not reconnect:
self._reset_connection_attributes()
await self._connect(hostname=hostname, port=port, reconnect=reconnect, **kwargs)
# Set logger name.
if self.server_tag:
self.logger = logging.getLogger(self.__class__.__name__ + ':' + self.server_tag)
self.eventloop.create_task(self.handle_forever())
async def disconnect(self, expected=True):
""" Disconnect from server. """
if self.connected:
# Schedule disconnect.
await self._disconnect(expected)
async def _disconnect(self, expected):
# Shutdown connection.
await self.connection.disconnect()
# Reset any attributes.
self._reset_attributes()
# Callback.
await self.on_disconnect(expected)
# Shut down event loop.
if expected and self.own_eventloop:
self.connection.stop()
async def _connect(self, hostname, port, reconnect=False, channels=None,
encoding=protocol.DEFAULT_ENCODING, source_address=None):
""" Connect to IRC host. """
# Create connection if we can't reuse it.
if not reconnect or not self.connection:
self._autojoin_channels = channels or []
self.connection = connection.Connection(hostname, port, source_address=source_address,
eventloop=self.eventloop)
self.encoding = encoding
# Connect.
await self.connection.connect()
def _reconnect_delay(self):
""" Calculate reconnection delay. """
if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED:
if self._reconnect_attempts >= len(self.RECONNECT_DELAYS):
return self.RECONNECT_DELAYS[-1]
return self.RECONNECT_DELAYS[self._reconnect_attempts]
return 0
## Internal database management.
def _create_channel(self, channel):
self.channels[channel] = {
'users': set(),
}
def _destroy_channel(self, channel):
# Copy set to prevent a runtime error when destroying the user.
for user in set(self.channels[channel]['users']):
self._destroy_user(user, channel)
del self.channels[channel]
def _create_user(self, nickname):
# Servers are NOT users.
if not nickname or '.' in nickname:
return
self.users[nickname] = {
'nickname': nickname,
'username': None,
'realname': None,
'hostname': None
}
async def _sync_user(self, nick, metadata):
# Create user in database.
if nick not in self.users:
await self._create_user(nick)
if nick not in self.users:
return
self.users[nick].update(metadata)
async def _rename_user(self, user, new):
if user in self.users:
self.users[new] = self.users[user]
self.users[new]['nickname'] = new
del self.users[user]
else:
await self._create_user(new)
if new not in self.users:
return
for ch in self.channels.values():
# Rename user in channel list.
if user in ch['users']:
ch['users'].discard(user)
ch['users'].add(new)
def _destroy_user(self, nickname, channel=None):
if channel:
channels = [self.channels[channel]]
else:
channels = self.channels.values()
for ch in channels:
# Remove from nicklist.
ch['users'].discard(nickname)
# If we're not in any common channels with the user anymore, we have no reliable way to keep their info up-to-date.
# Remove the user.
if not channel or not any(nickname in ch['users'] for ch in self.channels.values()):
del self.users[nickname]
def _parse_user(self, data):
""" Parse user and return nickname, metadata tuple. """
raise NotImplementedError()
def _format_user_mask(self, nickname):
user = self.users.get(nickname, {"nickname": nickname, "username": "*", "hostname": "*"})
return self._format_host_mask(user['nickname'], user['username'] or '*',
user['hostname'] or '*')
def _format_host_mask(self, nick, user, host):
return '{n}!{u}@{h}'.format(n=nick, u=user, h=host)
## IRC helpers.
def is_channel(self, chan):
""" Check if given argument is a channel name or not. """
return True
def in_channel(self, channel):
""" Check if we are currently in the given channel. """
return channel in self.channels.keys()
def is_same_nick(self, left, right):
""" Check if given nicknames are equal. """
return left == right
def is_same_channel(self, left, right):
""" Check if given channel names are equal. """
return left == right
## IRC attributes.
@property
def connected(self):
""" Whether or not we are connected. """
return self.connection and self.connection.connected
@property
def server_tag(self):
if self.connected and self.connection.hostname:
if self.network:
tag = self.network.lower()
else:
tag = self.connection.hostname.lower()
# Remove hostname prefix.
if tag.startswith('irc.'):
tag = tag[4:]
# Check if host is either an FQDN or IPv4.
if '.' in tag:
# Attempt to cut off TLD.
host, suffix = tag.rsplit('.', 1)
# Make sure we aren't cutting off the last octet of an IPv4.
try:
int(suffix)
except ValueError:
tag = host
return tag
return None
## IRC API.
async def raw(self, message):
""" Send raw command. """
await self._send(message)
async def rawmsg(self, command, *args, **kwargs):
""" Send raw message. """
message = str(self._create_message(command, *args, **kwargs))
await self._send(message)
## Overloadable callbacks.
async def on_connect(self):
""" Callback called when the client has connected successfully. """
# Reset reconnect attempts.
self._reconnect_attempts = 0
async def on_disconnect(self, expected):
if not expected:
# Unexpected disconnect. Reconnect?
if self.RECONNECT_ON_ERROR and (
self.RECONNECT_MAX_ATTEMPTS is None or self._reconnect_attempts < self.RECONNECT_MAX_ATTEMPTS):
# Calculate reconnect delay.
delay = self._reconnect_delay()
self._reconnect_attempts += 1
if delay > 0:
self.logger.error(
'Unexpected disconnect. Attempting to reconnect within %s seconds.', delay)
else:
self.logger.error('Unexpected disconnect. Attempting to reconnect.')
# Wait and reconnect.
await sleep(delay)
await self.connect(reconnect=True)
else:
self.logger.error('Unexpected disconnect. Giving up.')
## Message dispatch.
def _has_message(self):
""" Whether or not we have messages available for processing. """
raise NotImplementedError()
def _create_message(self, command, *params, **kwargs):
raise NotImplementedError()
def _parse_message(self):
raise NotImplementedError()
async def _send(self, input):
if not isinstance(input, (bytes, str)):
input = str(input)
if isinstance(input, str):
input = input.encode(self.encoding)
self.logger.debug('>> %s', input.decode(self.encoding))
await self.connection.send(input)
async def handle_forever(self):
""" Handle data forever. """
while self.connected:
try:
data = await self.connection.recv(timeout=self.READ_TIMEOUT)
except asyncio.TimeoutError:
self.logger.warning(
'>> Receive timeout reached, sending ping to check connection state...')
try:
await self.rawmsg("PING", self.server_tag)
data = await self.connection.recv(timeout=self.READ_TIMEOUT)
except (asyncio.TimeoutError, ConnectionResetError):
data = None
if not data:
if self.connected:
await self.disconnect(expected=False)
break
await self.on_data(data)
## Raw message handlers.
async def on_data(self, data):
""" Handle received data. """
self._receive_buffer += data
while self._has_message():
message = self._parse_message()
self.eventloop.create_task(self.on_raw(message))
async def on_data_error(self, exception):
""" Handle error. """
self.logger.error('Encountered error on socket.',
exc_info=(type(exception), exception, None))
await self.disconnect(expected=False)
async def on_raw(self, message):
""" Handle a single message. """
self.logger.debug('<< %s', message._raw)
if not message._valid:
self.logger.warning('Encountered strictly invalid IRC message from server: %s',
message._raw)
if isinstance(message.command, int):
cmd = str(message.command).zfill(3)
else:
cmd = message.command
# Invoke dispatcher, if we have one.
method = 'on_raw_' + cmd.lower()
try:
# Set _top_level so __getattr__() can decide whether to return on_unknown or _ignored for unknown handlers.
# The reason for this is that features can always call super().on_raw_* safely and thus don't need to care for other features,
# while unknown messages for which no handlers exist at all are still logged.
self._handler_top_level = True
handler = getattr(self, method)
self._handler_top_level = False
await handler(message)
except:
self.logger.exception('Failed to execute %s handler.', method)
async def on_unknown(self, message):
""" Unknown command. """
self.logger.warning('Unknown command: [%s] %s %s', message.source, message.command,
message.params)
async def _ignored(self, message):
""" Ignore message. """
...
def __getattr__(self, attr):
""" Return on_unknown or _ignored for unknown handlers, depending on the invocation type. """
# Is this a raw handler?
if attr.startswith('on_raw_'):
# Are we in on_raw() trying to find any message handler?
if self._handler_top_level:
# In that case, return the method that logs and possibly acts on unknown messages.
return self.on_unknown
# Are we in an existing handler calling super()?
# Just ignore it, then.
return self._ignored
# This isn't a handler, just raise an error.
raise AttributeError(attr)
# Bonus features
def event(self, func):
"""
Registers the specified `func` to handle events of the same name.
The func will always be called with, at least, the bot's `self` instance.
Returns decorated func, unmodified.
"""
if not func.__name__.startswith("on_"):
raise NameError("Event handlers must start with 'on_'.")
if not inspect.iscoroutinefunction(func):
raise AssertionError("Wrapped function {!r} must be an `async def` function.".format(func))
setattr(self, func.__name__, functools.partial(func, self))
return func
|
(nickname, fallback_nicknames=None, username=None, realname=None, eventloop=None, **kwargs)
|
42,270 |
pydle.client
|
__getattr__
|
Return on_unknown or _ignored for unknown handlers, depending on the invocation type.
|
def __getattr__(self, attr):
""" Return on_unknown or _ignored for unknown handlers, depending on the invocation type. """
# Is this a raw handler?
if attr.startswith('on_raw_'):
# Are we in on_raw() trying to find any message handler?
if self._handler_top_level:
# In that case, return the method that logs and possibly acts on unknown messages.
return self.on_unknown
# Are we in an existing handler calling super()?
# Just ignore it, then.
return self._ignored
# This isn't a handler, just raise an error.
raise AttributeError(attr)
|
(self, attr)
|
42,271 |
pydle.client
|
__init__
|
Create a client.
|
def __init__(self, nickname, fallback_nicknames=None, username=None, realname=None,
eventloop=None, **kwargs):
""" Create a client. """
self._nicknames = [nickname] + (fallback_nicknames or [])
self.username = username or nickname.lower()
self.realname = realname or nickname
if eventloop:
self.eventloop = eventloop
else:
self.eventloop = get_event_loop()
self.own_eventloop = not eventloop
self._reset_connection_attributes()
self._reset_attributes()
if kwargs:
self.logger.warning('Unused arguments: %s', ', '.join(kwargs.keys()))
|
(self, nickname, fallback_nicknames=None, username=None, realname=None, eventloop=None, **kwargs)
|
42,272 |
pydle.client
|
_connect
|
Connect to IRC host.
|
def run(self, *args, **kwargs):
""" Connect and run bot in event loop. """
self.eventloop.run_until_complete(self.connect(*args, **kwargs))
try:
self.eventloop.run_forever()
finally:
self.eventloop.stop()
|
(self, hostname, port, reconnect=False, channels=None, encoding='utf-8', source_address=None)
|
42,273 |
pydle.client
|
_create_channel
| null |
def _create_channel(self, channel):
self.channels[channel] = {
'users': set(),
}
|
(self, channel)
|
42,274 |
pydle.client
|
_create_message
| null |
def _create_message(self, command, *params, **kwargs):
raise NotImplementedError()
|
(self, command, *params, **kwargs)
|
42,275 |
pydle.client
|
_create_user
| null |
def _create_user(self, nickname):
# Servers are NOT users.
if not nickname or '.' in nickname:
return
self.users[nickname] = {
'nickname': nickname,
'username': None,
'realname': None,
'hostname': None
}
|
(self, nickname)
|
42,276 |
pydle.client
|
_destroy_channel
| null |
def _destroy_channel(self, channel):
# Copy set to prevent a runtime error when destroying the user.
for user in set(self.channels[channel]['users']):
self._destroy_user(user, channel)
del self.channels[channel]
|
(self, channel)
|
42,277 |
pydle.client
|
_destroy_user
| null |
def _destroy_user(self, nickname, channel=None):
if channel:
channels = [self.channels[channel]]
else:
channels = self.channels.values()
for ch in channels:
# Remove from nicklist.
ch['users'].discard(nickname)
# If we're not in any common channels with the user anymore, we have no reliable way to keep their info up-to-date.
# Remove the user.
if not channel or not any(nickname in ch['users'] for ch in self.channels.values()):
del self.users[nickname]
|
(self, nickname, channel=None)
|
42,278 |
pydle.client
|
_disconnect
| null |
def run(self, *args, **kwargs):
""" Connect and run bot in event loop. """
self.eventloop.run_until_complete(self.connect(*args, **kwargs))
try:
self.eventloop.run_forever()
finally:
self.eventloop.stop()
|
(self, expected)
|
42,279 |
pydle.client
|
_format_host_mask
| null |
def _format_host_mask(self, nick, user, host):
return '{n}!{u}@{h}'.format(n=nick, u=user, h=host)
|
(self, nick, user, host)
|
42,280 |
pydle.client
|
_format_user_mask
| null |
def _format_user_mask(self, nickname):
user = self.users.get(nickname, {"nickname": nickname, "username": "*", "hostname": "*"})
return self._format_host_mask(user['nickname'], user['username'] or '*',
user['hostname'] or '*')
|
(self, nickname)
|
42,281 |
pydle.client
|
_has_message
|
Whether or not we have messages available for processing.
|
def _has_message(self):
""" Whether or not we have messages available for processing. """
raise NotImplementedError()
|
(self)
|
42,282 |
pydle.client
|
_ignored
|
Ignore message.
|
def _parse_message(self):
raise NotImplementedError()
|
(self, message)
|
42,283 |
pydle.client
|
_parse_message
| null |
def _parse_message(self):
raise NotImplementedError()
|
(self)
|
42,284 |
pydle.client
|
_parse_user
|
Parse user and return nickname, metadata tuple.
|
def _parse_user(self, data):
""" Parse user and return nickname, metadata tuple. """
raise NotImplementedError()
|
(self, data)
|
42,285 |
pydle.client
|
_reconnect_delay
|
Calculate reconnection delay.
|
def _reconnect_delay(self):
""" Calculate reconnection delay. """
if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED:
if self._reconnect_attempts >= len(self.RECONNECT_DELAYS):
return self.RECONNECT_DELAYS[-1]
return self.RECONNECT_DELAYS[self._reconnect_attempts]
return 0
|
(self)
|
42,287 |
pydle.client
|
_reset_attributes
|
Reset attributes.
|
def _reset_attributes(self):
""" Reset attributes. """
# Record-keeping.
self.channels = {}
self.users = {}
# Low-level data stuff.
self._receive_buffer = b''
self._pending = {}
self._handler_top_level = False
# Misc.
self.logger = logging.getLogger(__name__)
# Public connection attributes.
self.nickname = DEFAULT_NICKNAME
self.network = None
|
(self)
|
42,288 |
pydle.client
|
_reset_connection_attributes
|
Reset connection attributes.
|
def _reset_connection_attributes(self):
""" Reset connection attributes. """
self.connection = None
self.encoding = None
self._autojoin_channels = []
self._reconnect_attempts = 0
|
(self)
|
42,291 |
pydle.client
|
connect
|
Connect to IRC server.
|
def run(self, *args, **kwargs):
""" Connect and run bot in event loop. """
self.eventloop.run_until_complete(self.connect(*args, **kwargs))
try:
self.eventloop.run_forever()
finally:
self.eventloop.stop()
|
(self, hostname=None, port=None, reconnect=False, **kwargs)
|
42,292 |
pydle.client
|
disconnect
|
Disconnect from server.
|
def run(self, *args, **kwargs):
""" Connect and run bot in event loop. """
self.eventloop.run_until_complete(self.connect(*args, **kwargs))
try:
self.eventloop.run_forever()
finally:
self.eventloop.stop()
|
(self, expected=True)
|
42,293 |
pydle.client
|
event
|
Registers the specified `func` to handle events of the same name.
The func will always be called with, at least, the bot's `self` instance.
Returns decorated func, unmodified.
|
def event(self, func):
"""
Registers the specified `func` to handle events of the same name.
The func will always be called with, at least, the bot's `self` instance.
Returns decorated func, unmodified.
"""
if not func.__name__.startswith("on_"):
raise NameError("Event handlers must start with 'on_'.")
if not inspect.iscoroutinefunction(func):
raise AssertionError("Wrapped function {!r} must be an `async def` function.".format(func))
setattr(self, func.__name__, functools.partial(func, self))
return func
|
(self, func)
|
42,294 |
pydle.client
|
handle_forever
|
Handle data forever.
|
def _parse_message(self):
raise NotImplementedError()
|
(self)
|
42,295 |
pydle.client
|
in_channel
|
Check if we are currently in the given channel.
|
def in_channel(self, channel):
""" Check if we are currently in the given channel. """
return channel in self.channels.keys()
|
(self, channel)
|
42,296 |
pydle.client
|
is_channel
|
Check if given argument is a channel name or not.
|
def is_channel(self, chan):
""" Check if given argument is a channel name or not. """
return True
|
(self, chan)
|
42,297 |
pydle.client
|
is_same_channel
|
Check if given channel names are equal.
|
def is_same_channel(self, left, right):
""" Check if given channel names are equal. """
return left == right
|
(self, left, right)
|
42,298 |
pydle.client
|
is_same_nick
|
Check if given nicknames are equal.
|
def is_same_nick(self, left, right):
""" Check if given nicknames are equal. """
return left == right
|
(self, left, right)
|
42,299 |
pydle.client
|
on_connect
|
Callback called when the client has connected successfully.
|
@property
def server_tag(self):
if self.connected and self.connection.hostname:
if self.network:
tag = self.network.lower()
else:
tag = self.connection.hostname.lower()
# Remove hostname prefix.
if tag.startswith('irc.'):
tag = tag[4:]
# Check if host is either an FQDN or IPv4.
if '.' in tag:
# Attempt to cut off TLD.
host, suffix = tag.rsplit('.', 1)
# Make sure we aren't cutting off the last octet of an IPv4.
try:
int(suffix)
except ValueError:
tag = host
return tag
return None
|
(self)
|
42,300 |
pydle.client
|
on_data
|
Handle received data.
|
def _parse_message(self):
raise NotImplementedError()
|
(self, data)
|
42,301 |
pydle.client
|
on_data_error
|
Handle error.
|
def _parse_message(self):
raise NotImplementedError()
|
(self, exception)
|
42,302 |
pydle.client
|
on_disconnect
| null |
@property
def server_tag(self):
if self.connected and self.connection.hostname:
if self.network:
tag = self.network.lower()
else:
tag = self.connection.hostname.lower()
# Remove hostname prefix.
if tag.startswith('irc.'):
tag = tag[4:]
# Check if host is either an FQDN or IPv4.
if '.' in tag:
# Attempt to cut off TLD.
host, suffix = tag.rsplit('.', 1)
# Make sure we aren't cutting off the last octet of an IPv4.
try:
int(suffix)
except ValueError:
tag = host
return tag
return None
|
(self, expected)
|
42,303 |
pydle.client
|
on_raw
|
Handle a single message.
|
def _parse_message(self):
raise NotImplementedError()
|
(self, message)
|
42,304 |
pydle.client
|
on_unknown
|
Unknown command.
|
def _parse_message(self):
raise NotImplementedError()
|
(self, message)
|
42,305 |
pydle.client
|
raw
|
Send raw command.
|
@property
def server_tag(self):
if self.connected and self.connection.hostname:
if self.network:
tag = self.network.lower()
else:
tag = self.connection.hostname.lower()
# Remove hostname prefix.
if tag.startswith('irc.'):
tag = tag[4:]
# Check if host is either an FQDN or IPv4.
if '.' in tag:
# Attempt to cut off TLD.
host, suffix = tag.rsplit('.', 1)
# Make sure we aren't cutting off the last octet of an IPv4.
try:
int(suffix)
except ValueError:
tag = host
return tag
return None
|
(self, message)
|
42,306 |
pydle.client
|
rawmsg
|
Send raw message.
|
@property
def server_tag(self):
if self.connected and self.connection.hostname:
if self.network:
tag = self.network.lower()
else:
tag = self.connection.hostname.lower()
# Remove hostname prefix.
if tag.startswith('irc.'):
tag = tag[4:]
# Check if host is either an FQDN or IPv4.
if '.' in tag:
# Attempt to cut off TLD.
host, suffix = tag.rsplit('.', 1)
# Make sure we aren't cutting off the last octet of an IPv4.
try:
int(suffix)
except ValueError:
tag = host
return tag
return None
|
(self, command, *args, **kwargs)
|
42,307 |
pydle.client
|
run
|
Connect and run bot in event loop.
|
def run(self, *args, **kwargs):
""" Connect and run bot in event loop. """
self.eventloop.run_until_complete(self.connect(*args, **kwargs))
try:
self.eventloop.run_forever()
finally:
self.eventloop.stop()
|
(self, *args, **kwargs)
|
42,308 |
pydle
|
Client
|
A fully featured IRC client.
|
class Client(featurize(*features.ALL)):
""" A fully featured IRC client. """
...
|
(*args, sasl_identity='', sasl_username=None, sasl_password=None, sasl_mechanism=None, **kwargs)
|
42,310 |
pydle.features.ircv3.sasl
|
__init__
| null |
def __init__(self, *args, sasl_identity='', sasl_username=None, sasl_password=None, sasl_mechanism=None, **kwargs):
super().__init__(*args, **kwargs)
self.sasl_identity = sasl_identity
self.sasl_username = sasl_username
self.sasl_password = sasl_password
self.sasl_mechanism = sasl_mechanism
|
(self, *args, sasl_identity='', sasl_username=None, sasl_password=None, sasl_mechanism=None, **kwargs)
|
42,311 |
pydle.features.ircv3.cap
|
_capability_negotiated
|
Mark capability as negotiated, and end negotiation if we're done.
|
def _capability_normalize(self, cap):
cap = cap.lstrip(PREFIXES).lower()
if CAPABILITY_VALUE_DIVIDER in cap:
cap, _, value = cap.partition(CAPABILITY_VALUE_DIVIDER)
else:
value = None
return cap, value
|
(self, capab)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.