desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Closes all adapters and as such the session'
| def close(self):
| for v in self.adapters.values():
v.close()
|
'Registers a connection adapter to a prefix.
Adapters are sorted in descending order by key length.'
| def mount(self, prefix, adapter):
| self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if (len(k) < len(prefix))]
for key in keys_to_move:
self.adapters[key] = self.adapters.pop(key)
|
'Like iteritems(), but with all lowercase keys.'
| def lower_items(self):
| return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
|
'Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in th... | def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
| self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs)
|
'Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to con... | def proxy_manager_for(self, proxy, **proxy_kwargs):
| if (not (proxy in self.proxy_manager)):
proxy_headers = self.proxy_headers(proxy)
self.proxy_manager[proxy] = proxy_from_url(proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs)
return self.proxy_manager[proxy]
|
'Verify a SSL certificate. This method should not be called from user
code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param conn: The urllib3 connection object associated with the cert.
:param url: The requested URL.
:param verify: Whether we should actually... | def cert_verify(self, conn, url, verify, cert):
| if (url.lower().startswith('https') and verify):
cert_loc = None
if (verify is not True):
cert_loc = verify
if (not cert_loc):
cert_loc = DEFAULT_CA_BUNDLE_PATH
if (not cert_loc):
raise Exception('Could not find a suitable SSL CA ... |
'Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param... | def build_response(self, req, resp):
| response = Response()
response.status_code = getattr(resp, 'status', None)
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, byt... |
'Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request.'
| def get_connection(self, url, proxies=None):
| proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
parsed = urlparse(url)
url = parsed.geturl()
conn = self.poolmanager.... |
'Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled
connections.'
| def close(self):
| self.poolmanager.clear()
|
'Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapte... | def request_url(self, request, proxies):
| proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
if (proxy and (scheme != 'https')):
url = urldefragauth(request.url)
else:
url = request.path_url
return url
|
'Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapter... | def add_headers(self, request, **kwargs):
| pass
|
'Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:cla... | def proxy_headers(self, proxy):
| headers = {}
(username, password) = get_auth_from_url(proxy)
if (username and password):
headers['Proxy-Authorization'] = _basic_auth_str(username, password)
return headers
|
'Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect ti... | def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
| conn = self.get_connection(request.url, proxies)
self.cert_verify(conn, request.url, verify, cert)
url = self.request_url(request, proxies)
self.add_headers(request)
chunked = (not ((request.body is None) or ('Content-Length' in request.headers)))
if isinstance(timeout, tuple):
try:
... |
'Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)'
| def is_package(self, fullname):
| return hasattr(self.__get_module(fullname), '__path__')
|
'Return None
Required, if is_package is implemented'
| def get_code(self, fullname):
| self.__get_module(fullname)
return None
|
'Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found.'
| def _fetch(self, key):
| save_interp = self.section.main.interpolation
self.section.main.interpolation = False
current_section = self.section
while True:
val = current_section.get(key)
if ((val is not None) and (not isinstance(val, Section))):
break
val = current_section.get('DEFAULT', {}).ge... |
'Implementation-dependent helper function.
Will be passed a match object corresponding to the interpolation
key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
key in the appropriate config file section (using the ``_fetch()``
helper function) and return a 3-tuple: (key, value, section)
``key`` is the na... | def _parse_match(self, match):
| raise NotImplementedError()
|
'* parent is the section above
* depth is the depth level of this section
* main is the main ConfigObj
* indict is a dictionary to initialise the section with'
| def __init__(self, parent, depth, main, indict=None, name=None):
| if (indict is None):
indict = {}
dict.__init__(self)
self.parent = parent
self.main = main
self.depth = depth
self.name = name
self._initialise()
for (entry, value) in indict.iteritems():
self[entry] = value
|
'Fetch the item and do string interpolation.'
| def __getitem__(self, key):
| val = dict.__getitem__(self, key)
if self.main.interpolation:
if isinstance(val, basestring):
return self._interpolate(key, val)
if isinstance(val, list):
def _check(entry):
if isinstance(entry, basestring):
return self._interpolate(key... |
'Correctly set a value.
Making dictionary values Section instances.
(We have to special case \'Section\' instances - which are also dicts)
Keys must be strings.
Values need only be strings (or lists of strings) if
``main.stringify`` is set.
``unrepr`` must be set when setting a value to a dictionary, without
creating a... | def __setitem__(self, key, value, unrepr=False):
| if (not isinstance(key, basestring)):
raise ValueError(('The key "%s" is not a string.' % key))
if (key not in self.comments):
self.comments[key] = []
self.inline_comments[key] = ''
if (key in self.defaults):
self.defaults.remove(key)
if isinstance(value... |
'Remove items from the sequence when deleting.'
| def __delitem__(self, key):
| dict.__delitem__(self, key)
if (key in self.scalars):
self.scalars.remove(key)
else:
self.sections.remove(key)
del self.comments[key]
del self.inline_comments[key]
|
'A version of ``get`` that doesn\'t bypass string interpolation.'
| def get(self, key, default=None):
| try:
return self[key]
except KeyError:
return default
|
'A version of update that uses our ``__setitem__``.'
| def update(self, indict):
| for entry in indict:
self[entry] = indict[entry]
|
'\'D.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=MISSING):
| try:
val = self[key]
except KeyError:
if (default is MISSING):
raise
val = default
else:
del self[key]
return val
|
'Pops the first (key,val)'
| def popitem(self):
| sequence = (self.scalars + self.sections)
if (not sequence):
raise KeyError(": 'popitem(): dictionary is empty'")
key = sequence[0]
val = self[key]
del self[key]
return (key, val)
|
'A version of clear that also affects scalars/sections
Also clears comments and configspec.
Leaves other attributes alone :
depth/main/parent are not affected'
| def clear(self):
| dict.clear(self)
self.scalars = []
self.sections = []
self.comments = {}
self.inline_comments = {}
self.configspec = None
self.defaults = []
self.extra_values = []
|
'A version of setdefault that sets sequence if appropriate.'
| def setdefault(self, key, default=None):
| try:
return self[key]
except KeyError:
self[key] = default
return self[key]
|
'D.items() -> list of D\'s (key, value) pairs, as 2-tuples'
| def items(self):
| return zip((self.scalars + self.sections), self.values())
|
'D.keys() -> list of D\'s keys'
| def keys(self):
| return (self.scalars + self.sections)
|
'D.values() -> list of D\'s values'
| def values(self):
| return [self[key] for key in (self.scalars + self.sections)]
|
'D.iteritems() -> an iterator over the (key, value) items of D'
| def iteritems(self):
| return iter(self.items())
|
'D.iterkeys() -> an iterator over the keys of D'
| def iterkeys(self):
| return iter((self.scalars + self.sections))
|
'D.itervalues() -> an iterator over the values of D'
| def itervalues(self):
| return iter(self.values())
|
'x.__repr__() <==> repr(x)'
| def __repr__(self):
| def _getval(key):
try:
return self[key]
except MissingInterpolationOption:
return dict.__getitem__(self, key)
return ('{%s}' % ', '.join([('%s: %s' % (repr(key), repr(_getval(key)))) for key in (self.scalars + self.sections)]))
|
'Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict()
>>> n == a
1
>>> n is a
0'
| def dict(self):
| newdict = {}
for entry in self:
this_entry = self[entry]
if isinstance(this_entry, Section):
this_entry = this_entry.dict()
elif isinstance(this_entry, list):
this_entry = list(this_entry)
elif isinstance(this_entry, tuple):
this_entry = tuple(... |
'A recursive update - useful for merging config files.
>>> a = \'\'\'[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file\'\'\'.splitlines()
>>> b = \'\'\'# File is user.ini
... [section1]
... option1 = False
... # end of file\'\'\'.splitlines()
>>> c1 ... | def merge(self, indict):
| for (key, val) in indict.items():
if ((key in self) and isinstance(self[key], dict) and isinstance(val, dict)):
self[key].merge(val)
else:
self[key] = val
|
'Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments.'
| def rename(self, oldkey, newkey):
| if (oldkey in self.scalars):
the_list = self.scalars
elif (oldkey in self.sections):
the_list = self.sections
else:
raise KeyError(('Key "%s" not found.' % oldkey))
pos = the_list.index(oldkey)
val = self[oldkey]
dict.__delitem__(self, oldkey)
dict.__setitem_... |
'Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror
unless ``raise_errors=False``, in which case set the return value to
``False``.
Any unrecognised keyword arguments you pass to walk, will be pased on
to the fun... | def walk(self, function, raise_errors=True, call_on_sections=False, **keywargs):
| out = {}
for i in range(len(self.scalars)):
entry = self.scalars[i]
try:
val = function(self, entry, **keywargs)
entry = self.scalars[i]
out[entry] = val
except Exception:
if raise_errors:
raise
else:
... |
'Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` ... | def as_bool(self, key):
| val = self[key]
if (val == True):
return True
elif (val == False):
return False
else:
try:
if (not isinstance(val, basestring)):
raise KeyError()
else:
return self.main._bools[val.lower()]
except KeyError:
... |
'A convenience method which coerces the specified value to an integer.
If the value is an invalid literal for ``int``, a ``ValueError`` will
be raised.
>>> a = ConfigObj()
>>> a[\'a\'] = \'fish\'
>>> a.as_int(\'a\')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: \'fish\'
>>> a[\'... | def as_int(self, key):
| return int(self[key])
|
'A convenience method which coerces the specified value to a float.
If the value is an invalid literal for ``float``, a ``ValueError`` will
be raised.
>>> a = ConfigObj()
>>> a[\'a\'] = \'fish\'
>>> a.as_float(\'a\')
Traceback (most recent call last):
ValueError: invalid literal for float(): fish
>>> a[\'b\'] = \'1\'
>... | def as_float(self, key):
| return float(self[key])
|
'A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a[\'a\'] = 1
>>> a.as_list(\'a\')
[1]
>>> a[\'a\'] = (1,)
>>> a.as_list(\'a\')
[1]
>>> a[\'a\'] = [1]
>>> a.as_list(\'a\')
[1]'
| def as_list(self, key):
| result = self[key]
if isinstance(result, (tuple, list)):
return list(result)
return [result]
|
'Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
If there is no default value for this key, ``KeyError`` is raised.'
| def restore_default(self, key):
| default = self.default_values[key]
dict.__setitem__(self, key, default)
if (key not in self.defaults):
self.defaults.append(key)
return default
|
'Recursively restore default values to all members
that have them.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
It doesn\'t delete or modify entries without default values.'
| def restore_defaults(self):
| for key in self.default_values:
self.restore_default(key)
for section in self.sections:
self[section].restore_defaults()
|
'Parse a config file or create a config file object.
``ConfigObj(infile=None, configspec=None, encoding=None,
interpolation=True, raise_errors=False, list_values=True,
create_empty=False, file_error=False, stringify=True,
indent_type=None, default_encoding=None, unrepr=False,
write_empty_values=False, _inspec=False)``'... | def __init__(self, infile=None, options=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False):
| self._inspec = _inspec
Section.__init__(self, self, 0, self)
infile = (infile or [])
_options = {'configspec': configspec, 'encoding': encoding, 'interpolation': interpolation, 'raise_errors': raise_errors, 'list_values': list_values, 'create_empty': create_empty, 'file_error': file_error, 'stringify': ... |
'Handle any BOM, and decode if necessary.
If an encoding is specified, that *must* be used - but the BOM should
still be removed (and the BOM attribute set).
(If the encoding is wrongly specified, then a BOM for an alternative
encoding won\'t be discovered or removed.)
If an encoding is not specified, UTF8 or UTF16 BOM... | def _handle_bom(self, infile):
| if ((self.encoding is not None) and (self.encoding.lower() not in BOM_LIST)):
return self._decode(infile, self.encoding)
if isinstance(infile, (list, tuple)):
line = infile[0]
else:
line = infile
if (self.encoding is not None):
enc = BOM_LIST[self.encoding.lower()]
... |
'Decode ASCII strings to unicode if a self.encoding is specified.'
| def _a_to_u(self, aString):
| if self.encoding:
return aString.decode('ascii')
else:
return aString
|
'Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list.'
| def _decode(self, infile, encoding):
| if isinstance(infile, basestring):
return infile.decode(encoding).splitlines(True)
for (i, line) in enumerate(infile):
if (not isinstance(line, unicode)):
infile[i] = line.decode(encoding)
return infile
|
'Decode element to unicode if necessary.'
| def _decode_element(self, line):
| if (not self.encoding):
return line
if (isinstance(line, str) and self.default_encoding):
return line.decode(self.default_encoding)
return line
|
'Used by ``stringify`` within validate, to turn non-string values
into strings.'
| def _str(self, value):
| if (not isinstance(value, basestring)):
return str(value)
else:
return value
|
'Actually parse the config file.'
| def _parse(self, infile):
| temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = (len(infile) - 1)
cur_index = (-1)
reset_comment = False
while (cur_index < maxline):
if reset_comment:
comment_... |
'Given a section and a depth level, walk back through the sections
parents to see if the depth level matches a previous section.
Return a reference to the right section,
or raise a SyntaxError.'
| def _match_depth(self, sect, depth):
| while (depth < sect.depth):
if (sect is sect.parent):
raise SyntaxError()
sect = sect.parent
if (sect.depth == depth):
return sect
raise SyntaxError()
|
'Handle an error according to the error settings.
Either raise the error or store it.
The error will have occured at ``cur_index``'
| def _handle_error(self, text, ErrorClass, infile, cur_index):
| line = infile[cur_index]
cur_index += 1
message = (text % cur_index)
error = ErrorClass(message, cur_index, line)
if self.raise_errors:
raise error
self._errors.append(error)
|
'Return an unquoted version of a value'
| def _unquote(self, value):
| if (not value):
raise SyntaxError
if ((value[0] == value[(-1)]) and (value[0] in ('"', "'"))):
value = value[1:(-1)]
return value
|
'Return a safely quoted version of a value.
Raise a ConfigObjError if the value cannot be safely quoted.
If multiline is ``True`` (default) then use triple quotes
if necessary.
* Don\'t quote values that don\'t need it.
* Recursively quote members of a list and return a comma joined list.
* Multiline is ``False`` for l... | def _quote(self, value, multiline=True):
| if (multiline and self.write_empty_values and (value == '')):
return ''
if (multiline and isinstance(value, (list, tuple))):
if (not value):
return ','
elif (len(value) == 1):
return (self._quote(value[0], multiline=False) + ',')
return ', '.join([self.... |
'Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)'
| def _handle_value(self, value):
| if self._inspec:
return (value, '')
if (not self.list_values):
mat = self._nolistvalue.match(value)
if (mat is None):
raise SyntaxError()
return mat.groups()
mat = self._valueexp.match(value)
if (mat is None):
raise SyntaxError()
(list_values, sing... |
'Extract the value, where we are in a multiline situation.'
| def _multiline(self, value, infile, cur_index, maxline):
| quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)
if (mat is not None):
retval = list(mat.groups())
retval.append(cur_index)
return retval
elif (newvalue.find(quot) !... |
'Parse the configspec.'
| def _handle_configspec(self, configspec):
| if (not isinstance(configspec, ConfigObj)):
try:
configspec = ConfigObj(configspec, raise_errors=True, file_error=True, _inspec=True)
except ConfigObjError as e:
raise ConfigspecError(('Parsing configspec failed: %s' % e))
except IOError as e:
rai... |
'Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__'
| def _set_configspec(self, section, copy):
| configspec = section.configspec
many = configspec.get('__many__')
if isinstance(many, dict):
for entry in section.sections:
if (entry not in configspec):
section[entry].configspec = many
for entry in configspec.sections:
if (entry == '__many__'):
c... |
'Write an individual line, for the write method'
| def _write_line(self, indent_string, entry, this_entry, comment):
| if (not self.unrepr):
val = self._decode_element(self._quote(this_entry))
else:
val = repr(this_entry)
return ('%s%s%s%s%s' % (indent_string, self._decode_element(self._quote(entry, multiline=False)), self._a_to_u(' = '), val, self._decode_element(comment)))
|
'Write a section marker line'
| def _write_marker(self, indent_string, depth, entry, comment):
| return ('%s%s%s%s%s' % (indent_string, self._a_to_u(('[' * depth)), self._quote(self._decode_element(entry), multiline=False), self._a_to_u((']' * depth)), self._decode_element(comment)))
|
'Deal with a comment.'
| def _handle_comment(self, comment):
| if (not comment):
return ''
start = self.indent_type
if (not comment.startswith('#')):
start += self._a_to_u(' # ')
return (start + comment)
|
'Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename
>>> a.filename = \'test.ini\'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj(\'test.ini\', raise_errors=True)
1
>>> import os
>>> os.remove(\'test.ini\')'
| def write(self, outfile=None, section=None):
| if (self.indent_type is None):
self.indent_type = DEFAULT_INDENT_TYPE
out = []
cs = self._a_to_u('#')
csp = self._a_to_u('# ')
if (section is None):
int_val = self.interpolation
self.interpolation = False
section = self
for line in self.initial_comment:
... |
'Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(validator)
(Normally having previously passed in the configspec when the ConfigObj
was created - you can dynamically assign a dictionary of checks ... | def validate(self, validator, preserve_errors=False, copy=False, section=None):
| if (section is None):
if (self.configspec is None):
raise ValueError('No configspec supplied.')
if preserve_errors:
from validate import VdtMissingValue
self._vdtMissingValue = VdtMissingValue
section = self
if copy:
section.initi... |
'Clear ConfigObj instance and restore to \'freshly created\' state.'
| def reset(self):
| self.clear()
self._initialise()
self.configspec = None
self._original_configspec = None
|
'Reload a ConfigObj from file.
This method raises a ``ReloadError`` if the ConfigObj doesn\'t have
a filename attribute pointing to a file.'
| def reload(self):
| if (not isinstance(self.filename, basestring)):
raise ReloadError()
filename = self.filename
current_options = {}
for entry in OPTION_DEFAULTS:
if (entry == 'configspec'):
continue
current_options[entry] = getattr(self, entry)
configspec = self._original_configspe... |
'A dummy check method, always returns the value unchanged.'
| def check(self, check, member, missing=False):
| if missing:
raise self.baseErrorClass()
return member
|
'See datetime.tzinfo.fromutc'
| def fromutc(self, dt):
| if ((dt.tzinfo is not None) and (dt.tzinfo is not self)):
raise ValueError('fromutc: dt.tzinfo is not self')
return (dt + self._utcoffset).replace(tzinfo=self)
|
'See datetime.tzinfo.utcoffset
is_dst is ignored for StaticTzInfo, and exists only to
retain compatibility with DstTzInfo.'
| def utcoffset(self, dt, is_dst=None):
| return self._utcoffset
|
'See datetime.tzinfo.dst
is_dst is ignored for StaticTzInfo, and exists only to
retain compatibility with DstTzInfo.'
| def dst(self, dt, is_dst=None):
| return _notime
|
'See datetime.tzinfo.tzname
is_dst is ignored for StaticTzInfo, and exists only to
retain compatibility with DstTzInfo.'
| def tzname(self, dt, is_dst=None):
| return self._tzname
|
'Convert naive time to local time'
| def localize(self, dt, is_dst=False):
| if (dt.tzinfo is not None):
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
|
'Correct the timezone information on the given datetime.
This is normally a no-op, as StaticTzInfo timezones never have
ambiguous cases to correct:
>>> from pytz import timezone
>>> gmt = timezone(\'GMT\')
>>> isinstance(gmt, StaticTzInfo)
True
>>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt)
>>> gmt.normalize(dt) is... | def normalize(self, dt, is_dst=False):
| if (dt.tzinfo is self):
return dt
if (dt.tzinfo is None):
raise ValueError('Naive time - no tzinfo set')
return dt.astimezone(self)
|
'See datetime.tzinfo.fromutc'
| def fromutc(self, dt):
| if ((dt.tzinfo is not None) and (getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos)):
raise ValueError('fromutc: dt.tzinfo is not self')
dt = dt.replace(tzinfo=None)
idx = max(0, (bisect_right(self._utc_transition_times, dt) - 1))
inf = self._transition_info[idx]
return (... |
'Correct the timezone information on the given datetime
If date arithmetic crosses DST boundaries, the tzinfo
is not magically adjusted. This method normalizes the
tzinfo to the correct one.
To test, first we need to do some setup
>>> from pytz import timezone
>>> utc = timezone(\'UTC\')
>>> eastern = timezone(\'US/Eas... | def normalize(self, dt):
| if (dt.tzinfo is None):
raise ValueError('Naive time - no tzinfo set')
offset = dt.tzinfo._utcoffset
dt = dt.replace(tzinfo=None)
dt = (dt - offset)
return self.fromutc(dt)
|
'Convert naive time to local time.
This method should be used to construct localtimes, rather
than passing a tzinfo argument to a datetime constructor.
is_dst is used to determine the correct timezone in the ambigous
period at the end of daylight saving time.
>>> from pytz import timezone
>>> fmt = \'%Y-%m-%d %H:%M:%S ... | def localize(self, dt, is_dst=False):
| if (dt.tzinfo is not None):
raise ValueError('Not naive datetime (tzinfo is already set)')
possible_loc_dt = set()
for delta in [timedelta(days=(-1)), timedelta(days=1)]:
loc_dt = (dt + delta)
idx = max(0, (bisect_right(self._utc_transition_times, loc_dt) - 1))
... |
'See datetime.tzinfo.utcoffset
The is_dst parameter may be used to remove ambiguity during DST
transitions.
>>> from pytz import timezone
>>> tz = timezone(\'America/St_Johns\')
>>> ambiguous = datetime(2009, 10, 31, 23, 30)
>>> tz.utcoffset(ambiguous, is_dst=False)
datetime.timedelta(-1, 73800)
>>> tz.utcoffset(ambigu... | def utcoffset(self, dt, is_dst=None):
| if (dt is None):
return None
elif (dt.tzinfo is not self):
dt = self.localize(dt, is_dst)
return dt.tzinfo._utcoffset
else:
return self._utcoffset
|
'See datetime.tzinfo.dst
The is_dst parameter may be used to remove ambiguity during DST
transitions.
>>> from pytz import timezone
>>> tz = timezone(\'America/St_Johns\')
>>> normal = datetime(2009, 9, 1)
>>> tz.dst(normal)
datetime.timedelta(0, 3600)
>>> tz.dst(normal, is_dst=False)
datetime.timedelta(0, 3600)
>>> tz... | def dst(self, dt, is_dst=None):
| if (dt is None):
return None
elif (dt.tzinfo is not self):
dt = self.localize(dt, is_dst)
return dt.tzinfo._dst
else:
return self._dst
|
'See datetime.tzinfo.tzname
The is_dst parameter may be used to remove ambiguity during DST
transitions.
>>> from pytz import timezone
>>> tz = timezone(\'America/St_Johns\')
>>> normal = datetime(2009, 9, 1)
>>> tz.tzname(normal)
\'NDT\'
>>> tz.tzname(normal, is_dst=False)
\'NDT\'
>>> tz.tzname(normal, is_dst=True)
\'... | def tzname(self, dt, is_dst=None):
| if (dt is None):
return self.zone
elif (dt.tzinfo is not self):
dt = self.localize(dt, is_dst)
return dt.tzinfo._tzname
else:
return self._tzname
|
'Convert naive time to local time'
| def localize(self, dt, is_dst=False):
| if (dt.tzinfo is not None):
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
|
'Correct the timezone information on the given datetime'
| def normalize(self, dt, is_dst=False):
| if (dt.tzinfo is self):
return dt
if (dt.tzinfo is None):
raise ValueError('Naive time - no tzinfo set')
return dt.astimezone(self)
|
'Backwards compatibility.'
| def __call__(self, iso3166_code):
| return self[iso3166_code]
|
'Convert naive time to local time'
| def localize(self, dt, is_dst=False):
| if (dt.tzinfo is not None):
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
|
'Correct the timezone information on the given datetime'
| def normalize(self, dt, is_dst=False):
| if (dt.tzinfo is None):
raise ValueError('Naive time - no tzinfo set')
return dt.replace(tzinfo=self)
|
'The Soup object is initialized as the \'root tag\', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser.'
| def __init__(self, markup='', features=None, builder=None, parse_only=None, from_encoding=None, exclude_encodings=None, **kwargs):
| if ('convertEntities' in kwargs):
warnings.warn('BS4 does not respect the convertEntities argument to the BeautifulSoup constructor. Entities are always converted to Unicode characters.')
if ('markupMassage' in kwargs):
del kwargs['markupMassage... |
'Create a new tag associated with this soup.'
| def new_tag(self, name, namespace=None, nsprefix=None, **attrs):
| return Tag(None, self.builder, name, namespace, nsprefix, attrs)
|
'Create a new NavigableString associated with this soup.'
| def new_string(self, s, subclass=NavigableString):
| return subclass(s)
|
'Add an object to the parse tree.'
| def object_was_parsed(self, o, parent=None, most_recent_element=None):
| parent = (parent or self.currentTag)
previous_element = (most_recent_element or self._most_recent_element)
next_element = previous_sibling = next_sibling = None
if isinstance(o, Tag):
next_element = o.next_element
next_sibling = o.next_sibling
previous_sibling = o.previous_siblin... |
'Pops the tag stack up to and including the most recent
instance of the given tag. If inclusivePop is false, pops the tag
stack up to but *not* including the most recent instqance of
the given tag.'
| def _popToTag(self, name, nsprefix=None, inclusivePop=True):
| if (name == self.ROOT_TAG_NAME):
return
most_recently_popped = None
stack_size = len(self.tagStack)
for i in range((stack_size - 1), 0, (-1)):
t = self.tagStack[i]
if ((name == t.name) and (nsprefix == t.prefix)):
if inclusivePop:
most_recently_popped ... |
'Push a start tag on to the stack.
If this method returns None, the tag was rejected by the
SoupStrainer. You should proceed as if the tag had not occured
in the document. For instance, if this was a self-closing tag,
don\'t call handle_endtag.'
| def handle_starttag(self, name, namespace, nsprefix, attrs):
| self.endData()
if (self.parse_only and (len(self.tagStack) <= 1) and (self.parse_only.text or (not self.parse_only.search_tag(name, attrs)))):
return None
tag = Tag(self, self.builder, name, namespace, nsprefix, attrs, self.currentTag, self._most_recent_element)
if (tag is None):
return ... |
'Returns a string or Unicode representation of this document.
To get Unicode, pass None for encoding.'
| def decode(self, pretty_print=False, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter='minimal'):
| if self.is_xml:
encoding_part = ''
if (eventual_encoding != None):
encoding_part = (' encoding="%s"' % eventual_encoding)
prefix = (u'<?xml version="1.0"%s?>\n' % encoding_part)
else:
prefix = u''
if (not pretty_print):
indent_level = None
else:
... |
':return: A 4-tuple (markup, original encoding, encoding
declared within markup, whether any characters had to be
replaced with REPLACEMENT CHARACTER).'
| def prepare_markup(self, markup, user_specified_encoding=None, document_declared_encoding=None, exclude_encodings=None):
| if isinstance(markup, unicode):
(yield (markup, None, None, False))
return
try_encodings = [user_specified_encoding, document_declared_encoding]
dammit = UnicodeDammit(markup, try_encodings, is_html=True, exclude_encodings=exclude_encodings)
(yield (dammit.markup, dammit.original_encodin... |
'See `TreeBuilder`.'
| def test_fragment_to_document(self, fragment):
| return (u'<html><head></head><body>%s</body></html>' % fragment)
|
'Move all of this tag\'s children into another tag.'
| def reparentChildren(self, new_parent):
| element = self.element
new_parent_element = new_parent.element
final_next_element = element.next_sibling
new_parents_last_descendant = new_parent_element._last_descendant(False, False)
if (len(new_parent_element.contents) > 0):
new_parents_last_child = new_parent_element.contents[(-1)]
... |
':yield: A series of 4-tuples.
(markup, encoding, declared encoding,
has undergone character replacement)
Each 4-tuple represents a strategy for parsing the document.'
| def prepare_markup(self, markup, user_specified_encoding=None, exclude_encodings=None, document_declared_encoding=None):
| if isinstance(markup, unicode):
(yield (markup, None, document_declared_encoding, False))
if isinstance(markup, unicode):
(yield (markup.encode('utf8'), 'utf8', document_declared_encoding, False))
is_html = (not self.is_xml)
try_encodings = [user_specified_encoding, document_declared_enc... |
'Find the currently active prefix for the given namespace.'
| def _prefix_for_namespace(self, namespace):
| if (namespace is None):
return None
for inverted_nsmap in reversed(self.nsmaps):
if ((inverted_nsmap is not None) and (namespace in inverted_nsmap)):
return inverted_nsmap[namespace]
return None
|
'Handle comments as Comment objects.'
| def comment(self, content):
| self.soup.endData()
self.soup.handle_data(content)
self.soup.endData(Comment)
|
'See `TreeBuilder`.'
| def test_fragment_to_document(self, fragment):
| return (u'<?xml version="1.0" encoding="utf-8"?>\n%s' % fragment)
|
'See `TreeBuilder`.'
| def test_fragment_to_document(self, fragment):
| return (u'<html><body>%s</body></html>' % fragment)
|
'Register a treebuilder based on its advertised features.'
| def register(self, treebuilder_class):
| for feature in treebuilder_class.features:
self.builders_for_feature[feature].insert(0, treebuilder_class)
self.builders.insert(0, treebuilder_class)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.