Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../lib/python2..../site-pac.../urllib3
File: _collections.py
from __future__ import absolute_import
[0] Fix | Delete
try:
[1] Fix | Delete
from collections.abc import Mapping, MutableMapping
[2] Fix | Delete
except ImportError:
[3] Fix | Delete
from collections import Mapping, MutableMapping
[4] Fix | Delete
try:
[5] Fix | Delete
from threading import RLock
[6] Fix | Delete
except ImportError: # Platform-specific: No threads available
[7] Fix | Delete
class RLock:
[8] Fix | Delete
def __enter__(self):
[9] Fix | Delete
pass
[10] Fix | Delete
[11] Fix | Delete
def __exit__(self, exc_type, exc_value, traceback):
[12] Fix | Delete
pass
[13] Fix | Delete
[14] Fix | Delete
[15] Fix | Delete
from collections import OrderedDict
[16] Fix | Delete
from .exceptions import InvalidHeader
[17] Fix | Delete
from .packages.six import iterkeys, itervalues, PY3
[18] Fix | Delete
[19] Fix | Delete
[20] Fix | Delete
__all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']
[21] Fix | Delete
[22] Fix | Delete
[23] Fix | Delete
_Null = object()
[24] Fix | Delete
[25] Fix | Delete
[26] Fix | Delete
class RecentlyUsedContainer(MutableMapping):
[27] Fix | Delete
"""
[28] Fix | Delete
Provides a thread-safe dict-like container which maintains up to
[29] Fix | Delete
``maxsize`` keys while throwing away the least-recently-used keys beyond
[30] Fix | Delete
``maxsize``.
[31] Fix | Delete
[32] Fix | Delete
:param maxsize:
[33] Fix | Delete
Maximum number of recent elements to retain.
[34] Fix | Delete
[35] Fix | Delete
:param dispose_func:
[36] Fix | Delete
Every time an item is evicted from the container,
[37] Fix | Delete
``dispose_func(value)`` is called. Callback which will get called
[38] Fix | Delete
"""
[39] Fix | Delete
[40] Fix | Delete
ContainerCls = OrderedDict
[41] Fix | Delete
[42] Fix | Delete
def __init__(self, maxsize=10, dispose_func=None):
[43] Fix | Delete
self._maxsize = maxsize
[44] Fix | Delete
self.dispose_func = dispose_func
[45] Fix | Delete
[46] Fix | Delete
self._container = self.ContainerCls()
[47] Fix | Delete
self.lock = RLock()
[48] Fix | Delete
[49] Fix | Delete
def __getitem__(self, key):
[50] Fix | Delete
# Re-insert the item, moving it to the end of the eviction line.
[51] Fix | Delete
with self.lock:
[52] Fix | Delete
item = self._container.pop(key)
[53] Fix | Delete
self._container[key] = item
[54] Fix | Delete
return item
[55] Fix | Delete
[56] Fix | Delete
def __setitem__(self, key, value):
[57] Fix | Delete
evicted_value = _Null
[58] Fix | Delete
with self.lock:
[59] Fix | Delete
# Possibly evict the existing value of 'key'
[60] Fix | Delete
evicted_value = self._container.get(key, _Null)
[61] Fix | Delete
self._container[key] = value
[62] Fix | Delete
[63] Fix | Delete
# If we didn't evict an existing value, we might have to evict the
[64] Fix | Delete
# least recently used item from the beginning of the container.
[65] Fix | Delete
if len(self._container) > self._maxsize:
[66] Fix | Delete
_key, evicted_value = self._container.popitem(last=False)
[67] Fix | Delete
[68] Fix | Delete
if self.dispose_func and evicted_value is not _Null:
[69] Fix | Delete
self.dispose_func(evicted_value)
[70] Fix | Delete
[71] Fix | Delete
def __delitem__(self, key):
[72] Fix | Delete
with self.lock:
[73] Fix | Delete
value = self._container.pop(key)
[74] Fix | Delete
[75] Fix | Delete
if self.dispose_func:
[76] Fix | Delete
self.dispose_func(value)
[77] Fix | Delete
[78] Fix | Delete
def __len__(self):
[79] Fix | Delete
with self.lock:
[80] Fix | Delete
return len(self._container)
[81] Fix | Delete
[82] Fix | Delete
def __iter__(self):
[83] Fix | Delete
raise NotImplementedError('Iteration over this class is unlikely to be threadsafe.')
[84] Fix | Delete
[85] Fix | Delete
def clear(self):
[86] Fix | Delete
with self.lock:
[87] Fix | Delete
# Copy pointers to all values, then wipe the mapping
[88] Fix | Delete
values = list(itervalues(self._container))
[89] Fix | Delete
self._container.clear()
[90] Fix | Delete
[91] Fix | Delete
if self.dispose_func:
[92] Fix | Delete
for value in values:
[93] Fix | Delete
self.dispose_func(value)
[94] Fix | Delete
[95] Fix | Delete
def keys(self):
[96] Fix | Delete
with self.lock:
[97] Fix | Delete
return list(iterkeys(self._container))
[98] Fix | Delete
[99] Fix | Delete
[100] Fix | Delete
class HTTPHeaderDict(MutableMapping):
[101] Fix | Delete
"""
[102] Fix | Delete
:param headers:
[103] Fix | Delete
An iterable of field-value pairs. Must not contain multiple field names
[104] Fix | Delete
when compared case-insensitively.
[105] Fix | Delete
[106] Fix | Delete
:param kwargs:
[107] Fix | Delete
Additional field-value pairs to pass in to ``dict.update``.
[108] Fix | Delete
[109] Fix | Delete
A ``dict`` like container for storing HTTP Headers.
[110] Fix | Delete
[111] Fix | Delete
Field names are stored and compared case-insensitively in compliance with
[112] Fix | Delete
RFC 7230. Iteration provides the first case-sensitive key seen for each
[113] Fix | Delete
case-insensitive pair.
[114] Fix | Delete
[115] Fix | Delete
Using ``__setitem__`` syntax overwrites fields that compare equal
[116] Fix | Delete
case-insensitively in order to maintain ``dict``'s api. For fields that
[117] Fix | Delete
compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``
[118] Fix | Delete
in a loop.
[119] Fix | Delete
[120] Fix | Delete
If multiple fields that are equal case-insensitively are passed to the
[121] Fix | Delete
constructor or ``.update``, the behavior is undefined and some will be
[122] Fix | Delete
lost.
[123] Fix | Delete
[124] Fix | Delete
>>> headers = HTTPHeaderDict()
[125] Fix | Delete
>>> headers.add('Set-Cookie', 'foo=bar')
[126] Fix | Delete
>>> headers.add('set-cookie', 'baz=quxx')
[127] Fix | Delete
>>> headers['content-length'] = '7'
[128] Fix | Delete
>>> headers['SET-cookie']
[129] Fix | Delete
'foo=bar, baz=quxx'
[130] Fix | Delete
>>> headers['Content-Length']
[131] Fix | Delete
'7'
[132] Fix | Delete
"""
[133] Fix | Delete
[134] Fix | Delete
def __init__(self, headers=None, **kwargs):
[135] Fix | Delete
super(HTTPHeaderDict, self).__init__()
[136] Fix | Delete
self._container = OrderedDict()
[137] Fix | Delete
if headers is not None:
[138] Fix | Delete
if isinstance(headers, HTTPHeaderDict):
[139] Fix | Delete
self._copy_from(headers)
[140] Fix | Delete
else:
[141] Fix | Delete
self.extend(headers)
[142] Fix | Delete
if kwargs:
[143] Fix | Delete
self.extend(kwargs)
[144] Fix | Delete
[145] Fix | Delete
def __setitem__(self, key, val):
[146] Fix | Delete
self._container[key.lower()] = [key, val]
[147] Fix | Delete
return self._container[key.lower()]
[148] Fix | Delete
[149] Fix | Delete
def __getitem__(self, key):
[150] Fix | Delete
val = self._container[key.lower()]
[151] Fix | Delete
return ', '.join(val[1:])
[152] Fix | Delete
[153] Fix | Delete
def __delitem__(self, key):
[154] Fix | Delete
del self._container[key.lower()]
[155] Fix | Delete
[156] Fix | Delete
def __contains__(self, key):
[157] Fix | Delete
return key.lower() in self._container
[158] Fix | Delete
[159] Fix | Delete
def __eq__(self, other):
[160] Fix | Delete
if not isinstance(other, Mapping) and not hasattr(other, 'keys'):
[161] Fix | Delete
return False
[162] Fix | Delete
if not isinstance(other, type(self)):
[163] Fix | Delete
other = type(self)(other)
[164] Fix | Delete
return (dict((k.lower(), v) for k, v in self.itermerged()) ==
[165] Fix | Delete
dict((k.lower(), v) for k, v in other.itermerged()))
[166] Fix | Delete
[167] Fix | Delete
def __ne__(self, other):
[168] Fix | Delete
return not self.__eq__(other)
[169] Fix | Delete
[170] Fix | Delete
if not PY3: # Python 2
[171] Fix | Delete
iterkeys = MutableMapping.iterkeys
[172] Fix | Delete
itervalues = MutableMapping.itervalues
[173] Fix | Delete
[174] Fix | Delete
__marker = object()
[175] Fix | Delete
[176] Fix | Delete
def __len__(self):
[177] Fix | Delete
return len(self._container)
[178] Fix | Delete
[179] Fix | Delete
def __iter__(self):
[180] Fix | Delete
# Only provide the originally cased names
[181] Fix | Delete
for vals in self._container.values():
[182] Fix | Delete
yield vals[0]
[183] Fix | Delete
[184] Fix | Delete
def pop(self, key, default=__marker):
[185] Fix | Delete
'''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
[186] Fix | Delete
If key is not found, d is returned if given, otherwise KeyError is raised.
[187] Fix | Delete
'''
[188] Fix | Delete
# Using the MutableMapping function directly fails due to the private marker.
[189] Fix | Delete
# Using ordinary dict.pop would expose the internal structures.
[190] Fix | Delete
# So let's reinvent the wheel.
[191] Fix | Delete
try:
[192] Fix | Delete
value = self[key]
[193] Fix | Delete
except KeyError:
[194] Fix | Delete
if default is self.__marker:
[195] Fix | Delete
raise
[196] Fix | Delete
return default
[197] Fix | Delete
else:
[198] Fix | Delete
del self[key]
[199] Fix | Delete
return value
[200] Fix | Delete
[201] Fix | Delete
def discard(self, key):
[202] Fix | Delete
try:
[203] Fix | Delete
del self[key]
[204] Fix | Delete
except KeyError:
[205] Fix | Delete
pass
[206] Fix | Delete
[207] Fix | Delete
def add(self, key, val):
[208] Fix | Delete
"""Adds a (name, value) pair, doesn't overwrite the value if it already
[209] Fix | Delete
exists.
[210] Fix | Delete
[211] Fix | Delete
>>> headers = HTTPHeaderDict(foo='bar')
[212] Fix | Delete
>>> headers.add('Foo', 'baz')
[213] Fix | Delete
>>> headers['foo']
[214] Fix | Delete
'bar, baz'
[215] Fix | Delete
"""
[216] Fix | Delete
key_lower = key.lower()
[217] Fix | Delete
new_vals = [key, val]
[218] Fix | Delete
# Keep the common case aka no item present as fast as possible
[219] Fix | Delete
vals = self._container.setdefault(key_lower, new_vals)
[220] Fix | Delete
if new_vals is not vals:
[221] Fix | Delete
vals.append(val)
[222] Fix | Delete
[223] Fix | Delete
def extend(self, *args, **kwargs):
[224] Fix | Delete
"""Generic import function for any type of header-like object.
[225] Fix | Delete
Adapted version of MutableMapping.update in order to insert items
[226] Fix | Delete
with self.add instead of self.__setitem__
[227] Fix | Delete
"""
[228] Fix | Delete
if len(args) > 1:
[229] Fix | Delete
raise TypeError("extend() takes at most 1 positional "
[230] Fix | Delete
"arguments ({0} given)".format(len(args)))
[231] Fix | Delete
other = args[0] if len(args) >= 1 else ()
[232] Fix | Delete
[233] Fix | Delete
if isinstance(other, HTTPHeaderDict):
[234] Fix | Delete
for key, val in other.iteritems():
[235] Fix | Delete
self.add(key, val)
[236] Fix | Delete
elif isinstance(other, Mapping):
[237] Fix | Delete
for key in other:
[238] Fix | Delete
self.add(key, other[key])
[239] Fix | Delete
elif hasattr(other, "keys"):
[240] Fix | Delete
for key in other.keys():
[241] Fix | Delete
self.add(key, other[key])
[242] Fix | Delete
else:
[243] Fix | Delete
for key, value in other:
[244] Fix | Delete
self.add(key, value)
[245] Fix | Delete
[246] Fix | Delete
for key, value in kwargs.items():
[247] Fix | Delete
self.add(key, value)
[248] Fix | Delete
[249] Fix | Delete
def getlist(self, key, default=__marker):
[250] Fix | Delete
"""Returns a list of all the values for the named field. Returns an
[251] Fix | Delete
empty list if the key doesn't exist."""
[252] Fix | Delete
try:
[253] Fix | Delete
vals = self._container[key.lower()]
[254] Fix | Delete
except KeyError:
[255] Fix | Delete
if default is self.__marker:
[256] Fix | Delete
return []
[257] Fix | Delete
return default
[258] Fix | Delete
else:
[259] Fix | Delete
return vals[1:]
[260] Fix | Delete
[261] Fix | Delete
# Backwards compatibility for httplib
[262] Fix | Delete
getheaders = getlist
[263] Fix | Delete
getallmatchingheaders = getlist
[264] Fix | Delete
iget = getlist
[265] Fix | Delete
[266] Fix | Delete
# Backwards compatibility for http.cookiejar
[267] Fix | Delete
get_all = getlist
[268] Fix | Delete
[269] Fix | Delete
def __repr__(self):
[270] Fix | Delete
return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))
[271] Fix | Delete
[272] Fix | Delete
def _copy_from(self, other):
[273] Fix | Delete
for key in other:
[274] Fix | Delete
val = other.getlist(key)
[275] Fix | Delete
if isinstance(val, list):
[276] Fix | Delete
# Don't need to convert tuples
[277] Fix | Delete
val = list(val)
[278] Fix | Delete
self._container[key.lower()] = [key] + val
[279] Fix | Delete
[280] Fix | Delete
def copy(self):
[281] Fix | Delete
clone = type(self)()
[282] Fix | Delete
clone._copy_from(self)
[283] Fix | Delete
return clone
[284] Fix | Delete
[285] Fix | Delete
def iteritems(self):
[286] Fix | Delete
"""Iterate over all header lines, including duplicate ones."""
[287] Fix | Delete
for key in self:
[288] Fix | Delete
vals = self._container[key.lower()]
[289] Fix | Delete
for val in vals[1:]:
[290] Fix | Delete
yield vals[0], val
[291] Fix | Delete
[292] Fix | Delete
def itermerged(self):
[293] Fix | Delete
"""Iterate over all headers, merging duplicate ones together."""
[294] Fix | Delete
for key in self:
[295] Fix | Delete
val = self._container[key.lower()]
[296] Fix | Delete
yield val[0], ', '.join(val[1:])
[297] Fix | Delete
[298] Fix | Delete
def items(self):
[299] Fix | Delete
return list(self.iteritems())
[300] Fix | Delete
[301] Fix | Delete
@classmethod
[302] Fix | Delete
def from_httplib(cls, message): # Python 2
[303] Fix | Delete
"""Read headers from a Python 2 httplib message object."""
[304] Fix | Delete
# python2.7 does not expose a proper API for exporting multiheaders
[305] Fix | Delete
# efficiently. This function re-reads raw lines from the message
[306] Fix | Delete
# object and extracts the multiheaders properly.
[307] Fix | Delete
obs_fold_continued_leaders = (' ', '\t')
[308] Fix | Delete
headers = []
[309] Fix | Delete
[310] Fix | Delete
for line in message.headers:
[311] Fix | Delete
if line.startswith(obs_fold_continued_leaders):
[312] Fix | Delete
if not headers:
[313] Fix | Delete
# We received a header line that starts with OWS as described
[314] Fix | Delete
# in RFC-7230 S3.2.4. This indicates a multiline header, but
[315] Fix | Delete
# there exists no previous header to which we can attach it.
[316] Fix | Delete
raise InvalidHeader(
[317] Fix | Delete
'Header continuation with no previous header: %s' % line
[318] Fix | Delete
)
[319] Fix | Delete
else:
[320] Fix | Delete
key, value = headers[-1]
[321] Fix | Delete
headers[-1] = (key, value + ' ' + line.strip())
[322] Fix | Delete
continue
[323] Fix | Delete
[324] Fix | Delete
key, value = line.split(':', 1)
[325] Fix | Delete
headers.append((key, value.strip()))
[326] Fix | Delete
[327] Fix | Delete
return cls(headers)
[328] Fix | Delete
[329] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function