desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Config: __getattr__ with setting value explicit'
| @TestArgs(('ADD_ALBUM_ART', True), ('ALBUM_ART_FORMAT', 'shmolder'), ('API_ENABLED', 1), ('API_KEY', 'Hello'))
def test__getattr__ConfValues(self, name, value):
| path = '/tmp/notexist'
self.config_mock['General'] = {name.lower(): value}
c = headphones.config.Config(path)
act = c.__getattr__(name)
self.assertEqual(act, value)
|
'Config: __getattr__ from config(by braces), default values'
| @TestArgs(('ADD_ALBUM_ART', 0), ('ALBUM_ART_FORMAT', 'folder'), ('API_ENABLED', 0), ('API_KEY', ''))
def test__getattr__ConfValuesDefault(self, name, value):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
res = c.__getattr__(name)
self.assertEqual(res, value)
|
'Config: __getattr__ from config (by dot), default values'
| def test__getattr__ConfValuesDefaultUsingDotNotation(self):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
self.assertEqual(c.ALBUM_ART_FORMAT, 'folder')
self.assertEqual(c.API_ENABLED, 0)
self.assertEqual(c.API_KEY, '')
|
'Config: __getattr__ access own attrs'
| def test__getattr__OwnAttributes(self):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
self.assertIsNotNone(c)
self.assertIn('<headphones.config.Config', c.__str__())
|
'Config: __setattr__ with setting value explicit'
| @TestArgs(('ADD_ALBUM_ART', True), ('ALBUM_ART_FORMAT', 'shmolder'), ('API_ENABLED', 1), ('API_KEY', 'Hello'))
def test__setattr__ConfValuesDefault(self, name, value):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
act = c.__setattr__(name, value)
self.assertEqual(self.config_mock['General'][name.lower()], value)
self.assertEqual(act, value)
|
'Config: __setattr__ with setting values using dot notation'
| def test__setattr__ExplicitSetUsingDotNotation(self):
| path = '/tmp/notexist'
c = headphones.config.Config(path)
act1 = c.ALBUM_ART_FORMAT = 'Apple'
act2 = c.API_ENABLED = True
act3 = c.API_KEY = 123
self.assertEqual(self.config_mock['General']['album_art_format'], 'Apple')
self.assertEqual(self.config_mock['General']['api_enabled'], 1)
self... |
'Config: get_extra_newznabs'
| @TestArgs(('', []), ('ABCDEF', [('A', 'B', 'C'), ('D', 'E', 'F')]), (['ABC', 'DEF'], []), ([1], []), ([1, 2], []), ([1, 2, 3], [(1, 2, 3)]), ([1, 2, 3, 'Aaa'], [(1, 2, 3)]), ([1, 2, 3, 'Aaa', 'Bbba'], [(1, 2, 3)]), ([1, 2, 3, 'Aaa', 'Bbba', 'Ccccc'], [(1, 2, 3), ('Aaa', 'Bbba', 'Ccccc')]), ([1, 2, 3, 'Aaa', 'Bbba', 'Cc... | path = '/tmp/notexist'
self.config_mock['Newznab'] = {'extra_newznabs': conf_value}
c = headphones.config.Config(path)
res = c.get_extra_newznabs()
self.assertEqual(res, expected)
|
'Config: clear_extra_newznabs'
| def test_clear_extra_newznabs(self):
| path = '/tmp/notexist'
random_value = 1827746
self.config_mock['Newznab'] = {'extra_newznabs': [1, 2, 3]}
self.config_mock['Newznab'] = {'do_not_touch': random_value}
c = headphones.config.Config(path)
res = c.clear_extra_newznabs()
self.assertIsNone(res)
self.assertEqual(self.config_moc... |
'Config: add_extra_newznab'
| @TestArgs(([], [''], ['']), ([], 'ABCDEF', ['A', 'B', 'C', 'D', 'E', 'F']), ([1, 2, [False, True]], ['3', [0, 0]], [1, 2, [False, True], '3', [0, 0]]))
def test_add_extra_newznab(self, initial, added, expected):
| path = '/tmp/notexist'
self.config_mock['Newznab'] = {'extra_newznabs': initial}
c = headphones.config.Config(path)
c.add_extra_newznab(added)
act = self.config_mock['Newznab']['extra_newznabs']
self.assertEqual(act, expected)
|
'Config: add_extra_newznab should raise on None adding'
| @TestArgs(None, [], [1, 2, 3], [True])
def test_add_extra_newznab_raise_on_none(self, initial):
| path = '/tmp/notexist'
self.config_mock['Newznab'] = {'extra_newznabs': initial}
c = headphones.config.Config(path)
with self.assertRaises(TypeError):
c.add_extra_newznab(None)
pass
|
'Config: get_extra_torznabs'
| @TestArgs(('', []), ('ABCDEF', [('A', 'B', 'C'), ('D', 'E', 'F')]), (['ABC', 'DEF'], []), ([1], []), ([1, 2], []), ([1, 2, 3], [(1, 2, 3)]), ([1, 2, 3, 'Aaa'], [(1, 2, 3)]), ([1, 2, 3, 'Aaa', 'Bbba'], [(1, 2, 3)]), ([1, 2, 3, 'Aaa', 'Bbba', 'Ccccc'], [(1, 2, 3), ('Aaa', 'Bbba', 'Ccccc')]), ([1, 2, 3, 'Aaa', 'Bbba', 'Cc... | path = '/tmp/notexist'
self.config_mock['Torznab'] = {'extra_torznabs': conf_value}
c = headphones.config.Config(path)
res = c.get_extra_torznabs()
self.assertEqual(res, expected)
|
'Config: clear_extra_torznabs'
| def test_clear_extra_torznabs(self):
| path = '/tmp/notexist'
random_value = (-1292721)
self.config_mock['Torznab'] = {'extra_torznabs': [1, 2, 3]}
self.config_mock['Torznab'] = {'do_not_touch': random_value}
c = headphones.config.Config(path)
res = c.clear_extra_torznabs()
self.assertIsNone(res)
self.assertEqual(self.config_... |
'Config: add_extra_torznab'
| @TestArgs(([], [''], ['']), ([], 'ABCDEF', ['A', 'B', 'C', 'D', 'E', 'F']), ([1, 2, [False, True]], ['3', [0, 0]], [1, 2, [False, True], '3', [0, 0]]))
def test_add_extra_torznab(self, initial, added, expected):
| path = '/tmp/notexist'
self.config_mock['Torznab'] = {'extra_torznabs': initial}
c = headphones.config.Config(path)
c.add_extra_torznab(added)
act = self.config_mock['Torznab']['extra_torznabs']
self.assertEqual(act, expected)
|
'Config: add_extra_torznab should raise on None adding'
| @TestArgs(None, [], [1, 2, 3], [True])
def test_add_extra_torznab_raise_on_none(self, initial):
| path = '/tmp/notexist'
self.config_mock['Torznab'] = {'extra_torznabs': initial}
c = headphones.config.Config(path)
with self.assertRaises(TypeError):
c.add_extra_torznab(None)
pass
|
'Add (key,value) pairs to this dictionary using iterable as an input.
:param items: input items.'
| def add_items(self, items):
| for (key, value) in items:
self.__setitem__(key, value)
|
'Add metadata tags read from media file to album metadata.
:param mf: MediaFile'
| def add_media_file(self, mf):
| md = {}
_media_file_to_dict(mf, md)
if (self._common is None):
self._common = md
else:
self._common = _intersect(self._common, md)
|
'Build case-insensitive, case-preserving dict from gathered metadata
tags.
:return: dictinary-like object filled with $variables based on common
tags.'
| def build(self):
| return MetadataDict(self._common)
|
'Override this function and instead of prompting just give the
username/password that were provided when the class was instantiated.'
| def prompt_user_passwd(self, host, realm):
| if (self.numTries == 0):
self.numTries = 1
return (self.username, self.password)
else:
return ('', '')
|
'helpers: check correctness of clean_name() function'
| def test_clean_name(self):
| cases = {u' Wei\xdfe & rose ': 'Weisse and rose', u'Multiple / spaces': 'Multiple spaces', u"Kevin's m\xb2": 'Kevins m2', u'Symphon\u0119y N\xba9': 'Symphoney No.9', u'\xc6\xe6\xdf\xf0\xde\u0132\u0133': u'AeaessdThIJ\u0131j', u'Obsessi\xf3 (Cerebral Apoplexy remix)': ... |
'helpers: check if clean_name() works on non-unicode input'
| def test_clean_name_nonunicode(self):
| input = 'foo $ bar/BAZ'
test = clean_name(input).lower()
expected = 'foo bar baz'
self.assertEqual(test, expected, 'check clean_name() works on non-unicode')
input = 'f\xc3\xb3\xc3\xb3 $ BAZ'
test = clean_name(input).lower()
expected = clean_name('%f\xc3\xb3\xc3... |
'Set up the lock'
| def __init__(self, minimum_delta=0):
| self.lock = threading.Lock()
self.last_used = 0
self.minimum_delta = minimum_delta
self.queue = Queue.Queue()
|
'Called when with lock: is invoked'
| def __enter__(self):
| self.lock.acquire()
delta = (time.time() - self.last_used)
sleep_amount = (self.minimum_delta - delta)
if (sleep_amount >= 0):
headphones.logger.debug('Sleeping %s (interval)', sleep_amount)
time.sleep(sleep_amount)
while (not self.queue.empty()):
try:
secon... |
'Called when exiting the with block.'
| def __exit__(self, type, value, traceback):
| self.last_used = time.time()
self.lock.release()
|
'Asynchronously add time to the next request. Can be called outside
of the lock context, but it is possible for the next lock holder
to not check the queue until after something adds time to it.'
| def snooze(self, seconds):
| headphones.logger.info('Adding %s to queue', seconds)
self.queue.put(seconds)
|
'Do nothing on enter'
| def __enter__(self):
| pass
|
'Do nothing on exit'
| def __exit__(self, type, value, traceback):
| pass
|
'Pass a musicbrainz id to this function (either ArtistID or AlbumID)'
| def get_artwork_from_cache(self, ArtistID=None, AlbumID=None):
| self.query_type = 'artwork'
if ArtistID:
self.id = ArtistID
self.id_type = 'artist'
else:
self.id = AlbumID
self.id_type = 'album'
if (self._exists('artwork') and self._is_current(filename=self.artwork_files[0])):
return self.artwork_files[0]
else:
sel... |
'Pass a musicbrainz id to this function (either ArtistID or AlbumID)'
| def get_thumb_from_cache(self, ArtistID=None, AlbumID=None):
| self.query_type = 'thumb'
if ArtistID:
self.id = ArtistID
self.id_type = 'artist'
else:
self.id = AlbumID
self.id_type = 'album'
if (self._exists('thumb') and self._is_current(filename=self.thumb_files[0])):
return self.thumb_files[0]
else:
self._updat... |
'Here we\'re just going to open up the last.fm url, grab the image links and return them
Won\'t save any image urls, or save the artwork in the cache. Useful for search results, etc.'
| def get_image_links(self, ArtistID=None, AlbumID=None):
| if ArtistID:
self.id_type = 'artist'
data = lastfm.request_lastfm('artist.getinfo', mbid=ArtistID, api_key=LASTFM_API_KEY)
if (not data):
return
try:
image_url = data['artist']['image'][(-1)]['#text']
except (KeyError, IndexError):
logger.d... |
'Pass a musicbrainz id to this function (either ArtistID or AlbumID)'
| def remove_from_cache(self, ArtistID=None, AlbumID=None):
| if ArtistID:
self.id = ArtistID
self.id_type = 'artist'
else:
self.id = AlbumID
self.id_type = 'album'
self.query_type = 'artwork'
if self._exists('artwork'):
for artwork_file in self.artwork_files:
try:
os.remove(artwork_file)
... |
'Since we call the same url for both info and artwork, we\'ll update both at the same time'
| def _update_cache(self):
| myDB = db.DBConnection()
if (self.id_type == 'artist'):
data = lastfm.request_lastfm('artist.getinfo', mbid=self.id, api_key=LASTFM_API_KEY)
if (not data):
dbartist = myDB.action('SELECT ArtistName, Type FROM artists WHERE ArtistID=?', [self.id]).fetchone()
... |
'uTorrent API need HTTP Basic Auth and cookie support for token verify.'
| def _make_opener(self, realm, base_url, username, password):
| auth = urllib2.HTTPBasicAuthHandler()
auth.add_password(realm=realm, uri=base_url, user=username, passwd=password)
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
cookie_jar = cookielib.CookieJar()
cookie_handler = urllib2.HTTPCookieProcessor(cookie_jar)
handlers = [auth, ... |
'Import hook for fetching lyrics automatically.'
| def imported(self, session, task):
| if self.config['auto']:
for item in task.imported_items():
self.fetch_item_lyrics(session.lib, logging.DEBUG, item, False, self.config['force'])
|
'Fetch and store lyrics for a single item. If ``write``, then the
lyrics will also be written to the file itself. The ``loglevel``
parameter controls the visibility of the function\'s status log
messages.'
| def fetch_item_lyrics(self, lib, loglevel, item, write, force):
| if ((not force) and item.lyrics):
log.log(loglevel, u'lyrics already present: {0} - {1}'.format(item.artist, item.title))
return
lyrics = None
for (artist, titles) in search_pairs(item):
lyrics = [self.get_lyrics(artist, title) for title in titles]
if any(lyric... |
'Fetch lyrics, trying each source in turn. Return a string or
None if no lyrics were found.'
| def get_lyrics(self, artist, title):
| for backend in self.backends:
lyrics = backend(artist, title)
if lyrics:
log.debug(u'got lyrics from backend: {0}'.format(backend.__name__))
return _scrape_strip_cruft(lyrics, True)
|
'Find art for the album being imported.'
| def fetch_art(self, session, task):
| if task.is_album:
if (task.choice_flag == importer.action.ASIS):
local = True
elif (task.choice_flag == importer.action.APPLY):
local = False
else:
return
path = art_for_album(task.album, task.paths, self.maxwidth, local)
if path:
... |
'Place the discovered art in the filesystem.'
| def assign_art(self, session, task):
| if (task in self.art_paths):
path = self.art_paths.pop(task)
album = task.album
src_removed = (config['import']['delete'].get(bool) or config['import']['move'].get(bool))
album.set_art(path, (not src_removed))
album.store()
if src_removed:
task.prune(path)... |
'cookielib has no legitimate use for this method; add it back if you find one.'
| def add_header(self, key, val):
| raise NotImplementedError('Cookie headers should be added with add_unredirected_header()')
|
'Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers'
| def __init__(self, headers):
| self._headers = headers
|
'Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).'
| def get(self, name, default=None, domain=None, path=None):
| try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
|
'Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.'
| def set(self, name, value, **kwargs):
| if (value is None):
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
|
'Dict-like iterkeys() that returns an iterator of names of cookies
from the jar. See itervalues() and iteritems().'
| def iterkeys(self):
| for cookie in iter(self):
(yield cookie.name)
|
'Dict-like keys() that returns a list of names of cookies from the
jar. See values() and items().'
| def keys(self):
| return list(self.iterkeys())
|
'Dict-like itervalues() that returns an iterator of values of cookies
from the jar. See iterkeys() and iteritems().'
| def itervalues(self):
| for cookie in iter(self):
(yield cookie.value)
|
'Dict-like values() that returns a list of values of cookies from the
jar. See keys() and items().'
| def values(self):
| return list(self.itervalues())
|
'Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. See iterkeys() and itervalues().'
| def iteritems(self):
| for cookie in iter(self):
(yield (cookie.name, cookie.value))
|
'Dict-like items() that returns a list of name-value tuples from the
jar. See keys() and values(). Allows client-code to call
``dict(RequestsCookieJar)`` and get a vanilla python dict of key value
pairs.'
| def items(self):
| return list(self.iteritems())
|
'Utility method to list all the domains in the jar.'
| def list_domains(self):
| domains = []
for cookie in iter(self):
if (cookie.domain not in domains):
domains.append(cookie.domain)
return domains
|
'Utility method to list all the paths in the jar.'
| def list_paths(self):
| paths = []
for cookie in iter(self):
if (cookie.path not in paths):
paths.append(cookie.path)
return paths
|
'Returns True if there are multiple domains in the jar.
Returns False otherwise.'
| def multiple_domains(self):
| domains = []
for cookie in iter(self):
if ((cookie.domain is not None) and (cookie.domain in domains)):
return True
domains.append(cookie.domain)
return False
|
'Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.'
| def get_dict(self, domain=None, path=None):
| dictionary = {}
for cookie in iter(self):
if (((domain is None) or (cookie.domain == domain)) and ((path is None) or (cookie.path == path))):
dictionary[cookie.name] = cookie.value
return dictionary
|
'Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).'
| def __getitem__(self, name):
| return self._find_no_duplicates(name)
|
'Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.'
| def __setitem__(self, name, value):
| self.set(name, value)
|
'Deletes a cookie given a name. Wraps ``cookielib.CookieJar``\'s
``remove_cookie_by_name()``.'
| def __delitem__(self, name):
| remove_cookie_by_name(self, name)
|
'Updates this jar with cookies from another CookieJar or dict-like'
| def update(self, other):
| if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other)
|
'Requests uses this method internally to get cookie values. Takes as
args name and optional domain and path. Returns a cookie.value. If
there are conflicting cookies, _find arbitrarily chooses one. See
_find_no_duplicates if you want an exception thrown if there are
conflicting cookies.'
| def _find(self, name, domain=None, path=None):
| for cookie in iter(self):
if (cookie.name == name):
if ((domain is None) or (cookie.domain == domain)):
if ((path is None) or (cookie.path == path)):
return cookie.value
raise KeyError(('name=%r, domain=%r, path=%r' % (name, domain, path)))
|
'Both ``__get_item__`` and ``get`` call this function: it\'s never
used elsewhere in Requests. Takes as args name and optional domain and
path. Returns a cookie.value. Throws KeyError if cookie is not found
and CookieConflictError if there are multiple cookies that match name
and optionally domain and path.'
| def _find_no_duplicates(self, name, domain=None, path=None):
| toReturn = None
for cookie in iter(self):
if (cookie.name == name):
if ((domain is None) or (cookie.domain == domain)):
if ((path is None) or (cookie.path == path)):
if (toReturn is not None):
raise CookieConflictError(('There ar... |
'Unlike a normal CookieJar, this class is pickleable.'
| def __getstate__(self):
| state = self.__dict__.copy()
state.pop('_cookies_lock')
return state
|
'Unlike a normal CookieJar, this class is pickleable.'
| def __setstate__(self, state):
| self.__dict__.update(state)
if ('_cookies_lock' not in self.__dict__):
self._cookies_lock = threading.RLock()
|
'Return a copy of this RequestsCookieJar.'
| def copy(self):
| new_cj = RequestsCookieJar()
new_cj.update(self)
return new_cj
|
'reset analyser, clear any state'
| def reset(self):
| self._mDone = False
self._mTotalChars = 0
self._mFreqChars = 0
|
'feed a character with known length'
| def feed(self, aBuf, aCharLen):
| if (aCharLen == 2):
order = self.get_order(aBuf)
else:
order = (-1)
if (order >= 0):
self._mTotalChars += 1
if (order < self._mTableSize):
if (512 > self._mCharToFreqOrder[order]):
self._mFreqChars += 1
|
'return confidence based on existing data'
| def get_confidence(self):
| if ((self._mTotalChars <= 0) or (self._mFreqChars <= MINIMUM_DATA_THRESHOLD)):
return SURE_NO
if (self._mTotalChars != self._mFreqChars):
r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars) * self._mTypicalDistributionRatio))
if (r < SURE_YES):
return r
return... |
'Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.'
| def get_redirect_location(self):
| if (self.status in self.REDIRECT_STATUSES):
return self.headers.get('location')
return False
|
'Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``HTTPResponse.read`` if bytes
are encoded on the wire (e.g, compressed).'
| def tell(self):
| return self._fp_bytes_read
|
'Set-up the _decoder attribute if necessar.'
| def _init_decoder(self):
| content_encoding = self.headers.get('content-encoding', '').lower()
if ((self._decoder is None) and (content_encoding in self.CONTENT_DECODERS)):
self._decoder = _get_decoder(content_encoding)
|
'Decode the data passed in and potentially flush the decoder.'
| def _decode(self, data, decode_content, flush_decoder):
| try:
if (decode_content and self._decoder):
data = self._decoder.decompress(data)
except (IOError, zlib.error) as e:
content_encoding = self.headers.get('content-encoding', '').lower()
raise DecodeError(('Received response with content-encoding: %s, but fail... |
'Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.'
| @contextmanager
def _error_catcher(self):
| try:
try:
(yield)
except SocketTimeout:
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except BaseSSLError as e:
if ('read operation timed out' not in str(e)):
raise
raise ReadTimeoutError(self._pool,... |
'Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn\'t make sense to cache partial content as the full
response.
:param decode_content:
If True, will at... | def read(self, amt=None, decode_content=None, cache_content=False):
| self._init_decoder()
if (decode_content is None):
decode_content = self.decode_content
if (self._fp is None):
return
flush_decoder = False
data = None
with self._error_catcher():
if (amt is None):
data = self._fp.read()
flush_decoder = True
... |
'A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compre... | def stream(self, amt=(2 ** 16), decode_content=None):
| if self.chunked:
for line in self.read_chunked(amt, decode_content=decode_content):
(yield line)
else:
while (not is_fp_closed(self._fp)):
data = self.read(amt=amt, decode_content=decode_content)
if data:
(yield data)
|
'Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.'
| @classmethod
def from_httplib(ResponseCls, r, **response_kw):
| headers = r.msg
if (not isinstance(headers, HTTPHeaderDict)):
if PY3:
headers = HTTPHeaderDict(headers.items())
else:
headers = HTTPHeaderDict.from_httplib(headers)
strict = getattr(r, 'strict', 0)
resp = ResponseCls(body=r, headers=headers, status=r.status, versi... |
'Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param decode_content:
If True, will attempt to decode the body based on the
\'content-encoding\' header.'
| def read_chunked(self, amt=None, decode_content=None):
| self._init_decoder()
if (not self.chunked):
raise ResponseNotChunked("Response is not chunked. Header 'transfer-encoding: chunked' is missing.")
if (self._original_response and is_response_to_head(self._original_response)):
self._original_response.close()
retu... |
'Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.'
| def _new_pool(self, scheme, host, port):
| pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if (scheme == 'http'):
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
return pool_cls(host, port, **kwargs)
|
'Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.'
| def clear(self):
| self.pools.clear()
|
'Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn\'t given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.'
| def connection_from_host(self, host, port=None, scheme='http'):
| if (not host):
raise LocationValueError('No host specified.')
scheme = (scheme or 'http')
port = (port or port_by_scheme.get(scheme, 80))
pool_key = (scheme, host, port)
with self.pools.lock:
pool = self.pools.get(pool_key)
if pool:
return pool
pool ... |
'Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn\'t pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.'
| def connection_from_url(self, url):
| u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
|
'Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.'
| def urlopen(self, method, url, redirect=True, **kw):
| u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if ('headers' not in kw):
kw['headers'] = self.headers
if ((self.proxy is not None) and (u.scheme == 'http')):
response = conn.urlopen(m... |
'Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.'
| def _set_proxy_headers(self, url, headers=None):
| headers_ = {'Accept': '*/*'}
netloc = parse_url(url).netloc
if netloc:
headers_['Host'] = netloc
if headers:
headers_.update(headers)
return headers_
|
'Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.'
| def urlopen(self, method, url, redirect=True, **kw):
| u = parse_url(url)
if (u.scheme == 'http'):
headers = kw.get('headers', self.headers)
kw['headers'] = self._set_proxy_headers(url, headers)
return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
|
'Initialize an ordered dictionary. Signature is the same as for
regular dictionaries, but keyword arguments are not recommended
because their insertion order is arbitrary.'
| def __init__(self, *args, **kwds):
| if (len(args) > 1):
raise TypeError(('expected at most 1 arguments, got %d' % len(args)))
try:
self.__root
except AttributeError:
self.__root = root = []
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
|
'od.__setitem__(i, y) <==> od[i]=y'
| def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
| if (key not in self):
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
|
'od.__delitem__(y) <==> del od[y]'
| def __delitem__(self, key, dict_delitem=dict.__delitem__):
| dict_delitem(self, key)
(link_prev, link_next, key) = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev
|
'od.__iter__() <==> iter(od)'
| def __iter__(self):
| root = self.__root
curr = root[1]
while (curr is not root):
(yield curr[2])
curr = curr[1]
|
'od.__reversed__() <==> reversed(od)'
| def __reversed__(self):
| root = self.__root
curr = root[0]
while (curr is not root):
(yield curr[2])
curr = curr[0]
|
'od.clear() -> None. Remove all items from od.'
| def clear(self):
| try:
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
except AttributeError:
pass
dict.clear(self)
|
'od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.'
| def popitem(self, last=True):
| if (not self):
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root[0]
link_prev = link[0]
link_prev[1] = root
root[0] = link_prev
else:
link = root[1]
link_next = link[1]
root[1] = link_next
link_next... |
'od.keys() -> list of keys in od'
| def keys(self):
| return list(self)
|
'od.values() -> list of values in od'
| def values(self):
| return [self[key] for key in self]
|
'od.items() -> list of (key, value) pairs in od'
| def items(self):
| return [(key, self[key]) for key in self]
|
'od.iterkeys() -> an iterator over the keys in od'
| def iterkeys(self):
| return iter(self)
|
'od.itervalues -> an iterator over the values in od'
| def itervalues(self):
| for k in self:
(yield self[k])
|
'od.iteritems -> an iterator over the (key, value) items in od'
| def iteritems(self):
| for k in self:
(yield (k, self[k]))
|
'od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, ... | def update(*args, **kwds):
| if (len(args) > 2):
raise TypeError(('update() takes at most 2 positional arguments (%d given)' % (len(args),)))
elif (not args):
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
other = ()
if (len(args) == 2)... |
'od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.'
| def pop(self, key, default=__marker):
| if (key in self):
result = self[key]
del self[key]
return result
if (default is self.__marker):
raise KeyError(key)
return default
|
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
| def setdefault(self, key, default=None):
| if (key in self):
return self[key]
self[key] = default
return default
|
'od.__repr__() <==> repr(od)'
| def __repr__(self, _repr_running={}):
| call_key = (id(self), _get_ident())
if (call_key in _repr_running):
return '...'
_repr_running[call_key] = 1
try:
if (not self):
return ('%s()' % (self.__class__.__name__,))
return ('%s(%r)' % (self.__class__.__name__, self.items()))
finally:
del _repr_run... |
'Return state information for pickling'
| def __reduce__(self):
| items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return (self.__class__, (items,))
|
'od.copy() -> a shallow copy of od'
| def copy(self):
| return self.__class__(self)
|
'OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).'
| @classmethod
def fromkeys(cls, iterable, value=None):
| d = cls()
for key in iterable:
d[key] = value
return d
|
'od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.'
| def __eq__(self, other):
| if isinstance(other, OrderedDict):
return ((len(self) == len(other)) and (self.items() == other.items()))
return dict.__eq__(self, other)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.