desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'The wire name of the operation. In many situations this is the same value as the ``name``, value, but in some services, the operation name exposed to the user is different from the operaiton name we send across the wire (e.g cloudfront). Any serialization code should use ``wire_name``.'
@property def wire_name(self):
return self._operation_model.get('name')
'Returns the streaming member\'s shape if any; or None otherwise.'
def _get_streaming_body(self, shape):
if (shape is None): return None payload = shape.serialization.get('payload') if (payload is not None): payload_shape = shape.members[payload] if (payload_shape.type_name == 'blob'): return payload_shape return None
':type members: dict :param members: The denormalized members. :return: self'
def with_members(self, members):
self._members = members return self
'Build the model based on the provided members. :rtype: botocore.model.StructureShape :return: The built StructureShape object.'
def build_model(self):
shapes = OrderedDict() denormalized = {'type': 'structure', 'members': self._members} self._build_model(denormalized, shapes, self.name) resolver = ShapeResolver(shape_map=shapes) return StructureShape(shape_name=self.name, shape_model=shapes[self.name], shape_resolver=resolver)
'Generate a unique shape name. This method will guarantee a unique shape name each time it is called with the same type. >>> s = ShapeNameGenerator() >>> s.new_shape_name(\'structure\') \'StructureType1\' >>> s.new_shape_name(\'structure\') \'StructureType2\' >>> s.new_shape_name(\'list\') \'ListType1\' >>> s.new_shape...
def new_shape_name(self, type_name):
self._name_cache[type_name] += 1 current_index = self._name_cache[type_name] return ('%sType%s' % (type_name.capitalize(), current_index))
'Validate parameters against a shape model. This method will validate the parameters against a provided shape model. All errors will be collected before returning to the caller. This means that this method will not stop at the first error, it will return all possible errors. :param params: User provided dict of parame...
def validate(self, params, shape):
errors = ValidationErrors() self._validate(params, shape, errors, name='') return errors
'Documents auto populated parameters It will remove any required marks for the parameter, remove the parameter from the example, and add a snippet about the parameter being autopopulated in the description.'
def document_auto_populated_param(self, event_name, section, **kwargs):
if event_name.startswith('docs.request-params'): if (self.name in section.available_sections): section = section.get_section(self.name) if ('is-required' in section.available_sections): section.delete_section('is-required') description_section = section.ge...
':type service_name: str :param service_name: Name of the service to modify. :type parameter_name: str :param parameter_name: Name of the parameter to modify. :type operation_names: list :param operation_names: Operation names to modify.'
def __init__(self, service_name, parameter_name, operation_names):
self._parameter_name = parameter_name self._params_events = set() self._example_events = set() param_template = 'docs.request-params.%s.%s.complete-section' example_template = 'docs.request-example.%s.%s.complete-section' for name in operation_names: self._params_events.add((param_templa...
'Documents an entire service. :returns: The reStructured text of the documented service.'
def document_service(self):
doc_structure = DocumentStructure(self._service_name, section_names=self.sections, target='html') self.title(doc_structure.get_section('title')) self.table_of_contents(doc_structure.get_section('table-of-contents')) self.client_api(doc_structure.get_section('client-api')) self.paginator_api(doc_stru...
'Fills out the documentation for a section given a model shape. :param section: The section to write the documentation to. :param shape: The shape of the operation. :type include: Dictionary where keys are parameter names and values are the shapes of the parameter names. :param include: The parameter shapes to include ...
def document_params(self, section, shape, include=None, exclude=None):
history = [] self.traverse_and_document_shape(section=section, shape=shape, history=history, name=None, include=include, exclude=exclude)
'Documents a client and its methods :param section: The section to write to.'
def document_client(self, section):
self._add_title(section) self._add_class_signature(section) client_methods = get_instance_public_methods(self._client) self._add_client_intro(section, client_methods) self._add_client_methods(section, client_methods)
'Documents the various paginators for a service param section: The section to write to.'
def document_paginators(self, section):
section.style.h2('Paginators') section.style.new_line() section.writeln('The available paginators are:') paginator_names = sorted(self._service_paginator_model._paginator_config) for paginator_name in paginator_names: section.style.li((':py:class:`%s.Paginator.%s`' % (self._client._...
'Generates an example based on a shape :param section: The section to write the documentation to. :param shape: The shape of the operation. :param prefix: Anything to be included before the example :type include: Dictionary where keys are parameter names and values are the shapes of the parameter names. :param include:...
def document_example(self, section, shape, prefix=None, include=None, exclude=None):
history = [] section.style.new_line() section.style.start_codeblock() if (prefix is not None): section.write(prefix) self.traverse_and_document_shape(section=section, shape=shape, history=history, include=include, exclude=exclude)
'The args and kwargs are the same as the underlying document generation function. These just get proxied to the underlying function.'
def __init__(self, *args, **kwargs):
super(LazyLoadedDocstring, self).__init__() self._gen_args = args self._gen_kwargs = kwargs self._docstring = None
'Expands tabs to spaces So this is a big hack in order to get lazy loaded docstring work for the ``help()``. In the ``help()`` function, ``pydoc`` and ``inspect`` are used. At some point the ``inspect.cleandoc`` method is called. To clean the docs ``expandtabs`` is called and that is where we override the method to gen...
def expandtabs(self, tabsize=8):
if (self._docstring is None): self._generate() return self._docstring.expandtabs(tabsize)
'Write content into the document.'
def write(self, content):
self._write(content)
'Write content on a newline.'
def writeln(self, content):
self._write(('%s%s\n' % (self.style.spaces(), content)))
'Returns the last content written to the document without removing it from the stack.'
def peek_write(self):
return self._writes[(-1)]
'Removes and returns the last content written to the stack.'
def pop_write(self):
return self._writes.pop()
'Places new content on the stack.'
def push_write(self, s):
self._writes.append(s)
'Returns the current content of the document as a string.'
def getvalue(self):
if self.hrefs: self.style.new_paragraph() for (refname, link) in self.hrefs.items(): self.style.link_target_definition(refname, link) return ''.join(self._writes).encode('utf-8')
'Provides a Hierarichial structure to a ReSTDocument You can write to it similiar to as you can to a ReSTDocument but has an innate structure for more orginaztion and abstraction. :param name: The name of the document :param section_names: A list of sections to be included in the document. :param target: The target doc...
def __init__(self, name, section_names=None, target='man', context=None):
super(DocumentStructure, self).__init__(target=target) self._name = name self._structure = OrderedDict() self._path = [self._name] self._context = {} if (context is not None): self._context = context if (section_names is not None): self._generate_structure(section_names)
'The name of the document structure'
@property def name(self):
return self._name
'A list of where to find a particular document structure in the overlying document structure.'
@property def path(self):
return self._path
'Adds a new section to the current document structure This document structure will be considered a section to the current document structure but will in itself be an entirely new document structure that can be written to and have sections as well :param name: The name of the section. :param context: A dictionary of dat...
def add_new_section(self, name, context=None):
section = self.__class__(name=name, target=self.target, context=context) section.path = (self.path + [name]) section.style.indentation = self.style.indentation section.translation_map = self.translation_map section.hrefs = self.hrefs self._structure[name] = section return section
'Retrieve a section'
def get_section(self, name):
return self._structure[name]
'Delete a section'
def delete_section(self, name):
del self._structure[name]
'Flushes a doc structure to a ReSTructed string The document is flushed out in a DFS style where sections and their subsections\' values are added to the string as they are visited.'
def flush_structure(self):
if (len(self.path) == 1): if self.hrefs: self.style.new_paragraph() for (refname, link) in self.hrefs.items(): self.style.link_target_definition(refname, link) value = self.getvalue() for (name, section) in self._structure.items(): value += section.flu...
'Traverses the tree, stripping out whitespace until text data is found :param node: The node to strip :return: True if non-whitespace data was found, False otherwise'
def _lstrip(self, node):
for child in node.children: if isinstance(child, DataNode): child.lstrip() if child.data: return True else: found = self._lstrip(child) if found: return True return False
'Literal code blocks are introduced by ending a paragraph with the special marker ::. The literal block must be indented (and, like all paragraphs, separated from the surrounding ones by blank lines).'
def codeblock(self, code):
self.start_codeblock() self.doc.writeln(code) self.end_codeblock()
'Documents the various waiters for a service. :param section: The section to write to.'
def document_waiters(self, section):
section.style.h2('Waiters') section.style.new_line() section.writeln('The available waiters are:') for waiter_name in self._service_waiter_model.waiter_names: section.style.li((':py:class:`%s.Waiter.%s`' % (self._client.__class__.__name__, waiter_name))) self._add_single_waiter(...
'Documents a single shared example based on its definition. :param example: The model of the example :param prefix: The prefix to use in the method example. :param section: The section to write to. :param operation_model: The model of the operation used in the example'
def document_shared_example(self, example, prefix, section, operation_model):
section.style.new_paragraph() section.write(example.get('description')) section.style.new_line() self.document_input(section, example, prefix, operation_model.input_shape) self.document_output(section, example, operation_model.output_shape)
':param section: The section to add the docs to. :param value: The input / output values representing the parameters that are included in the example. :param comments: The dictionary containing all the comments to be applied to the example. :param path: A list describing where the documenter is in traversing the parame...
def _document(self, section, value, comments, path, shape):
if isinstance(value, dict): self._document_dict(section, value, comments, path, shape) elif isinstance(value, list): self._document_list(section, value, comments, path, shape) elif isinstance(value, numbers.Number): self._document_number(section, value, path) elif (shape and (sha...
'Traverses and documents a shape Will take a self class and call its appropriate methods as a shape is traversed. :param section: The section to document. :param history: A list of the names of the shapes that have been traversed. :type include: Dictionary where keys are parameter names and values are the shapes of the...
def traverse_and_document_shape(self, section, shape, history, include=None, exclude=None, name=None, is_required=False):
param_type = shape.type_name if (shape.name in history): self.document_recursive_shape(section, shape, name=name) else: history.append(shape.name) is_top_level_param = (len(history) == 2) getattr(self, ('document_shape_type_%s' % param_type), self.document_shape_default)(sect...
'Sign a request before it goes out over the wire. :type operation_name: string :param operation_name: The name of the current operation, e.g. ``ListBuckets``. :type request: AWSRequest :param request: The request object to be sent over the wire. :type region_name: str :param region_name: The region to sign the request ...
def sign(self, operation_name, request, region_name=None, signing_type='standard', expires_in=None, signing_name=None):
if (region_name is None): region_name = self._region_name if (signing_name is None): signing_name = self._signing_name signature_version = self._choose_signer(operation_name, signing_type, request.context) self._event_emitter.emit('before-sign.{0}.{1}'.format(self._service_name, operatio...
'Allow setting the signature version via the choose-signer event. A value of `botocore.UNSIGNED` means no signing will be performed. :param operation_name: The operation to sign. :param signing_type: The type of signing that the signer is to be used for. :return: The signature version to sign with.'
def _choose_signer(self, operation_name, signing_type, context):
signing_type_suffix_map = {'presign-post': '-presign-post', 'presign-url': '-query'} suffix = signing_type_suffix_map.get(signing_type, '') signature_version = self._signature_version if ((signature_version is not botocore.UNSIGNED) and (not signature_version.endswith(suffix))): signature_versio...
'Get an auth instance which can be used to sign a request using the given signature version. :type signing_name: string :param signing_name: Service signing name. This is usually the same as the service name, but can differ. E.g. ``emr`` vs. ``elasticmapreduce``. :type region_name: string :param region_name: Name of th...
def get_auth_instance(self, signing_name, region_name, signature_version=None, **kwargs):
if (signature_version is None): signature_version = self._signature_version cls = botocore.auth.AUTH_TYPE_MAPS.get(signature_version) if (cls is None): raise UnknownSignatureVersionError(signature_version=signature_version) frozen_credentials = None if (self._credentials is not None)...
'Generates a presigned url :type request_dict: dict :param request_dict: The prepared request dictionary returned by ``botocore.awsrequest.prepare_request_dict()`` :type operation_name: str :param operation_name: The operation being signed. :type expires_in: int :param expires_in: The number of seconds the presigned ur...
def generate_presigned_url(self, request_dict, operation_name, expires_in=3600, region_name=None, signing_name=None):
request = create_request_object(request_dict) self.sign(operation_name, request, region_name, 'presign-url', expires_in, signing_name) request.prepare() return request.url
'Create a CloudFrontSigner. :type key_id: str :param key_id: The CloudFront Key Pair ID :type rsa_signer: callable :param rsa_signer: An RSA signer. Its only input parameter will be the message to be signed, and its output will be the signed content as a binary string. The hash algorithm needed by CloudFront is SHA-1.'...
def __init__(self, key_id, rsa_signer):
self.key_id = key_id self.rsa_signer = rsa_signer
'Creates a signed CloudFront URL based on given parameters. :type url: str :param url: The URL of the protected object :type date_less_than: datetime :param date_less_than: The URL will expire after that date and time :type policy: str :param policy: The custom policy, possibly built by self.build_policy() :rtype: str ...
def generate_presigned_url(self, url, date_less_than=None, policy=None):
if (((date_less_than is not None) and (policy is not None)) or ((date_less_than is None) and (policy is None))): e = 'Need to provide either date_less_than or policy, but not both' raise ValueError(e) if (date_less_than is not None): policy = self.build_policy(...
'A helper to build policy. :type resource: str :param resource: The URL or the stream filename of the protected object :type date_less_than: datetime :param date_less_than: The URL will expire after the time has passed :type date_greater_than: datetime :param date_greater_than: The URL will not be valid until this time...
def build_policy(self, resource, date_less_than, date_greater_than=None, ip_address=None):
moment = int(datetime2timestamp(date_less_than)) condition = OrderedDict({'DateLessThan': {'AWS:EpochTime': moment}}) if ip_address: if ('/' not in ip_address): ip_address += '/32' condition['IpAddress'] = {'AWS:SourceIp': ip_address} if date_greater_than: moment = in...
'Generates the url and the form fields used for a presigned s3 post :type request_dict: dict :param request_dict: The prepared request dictionary returned by ``botocore.awsrequest.prepare_request_dict()`` :type fields: dict :param fields: A dictionary of prefilled form fields to build on top of. :type conditions: list ...
def generate_presigned_post(self, request_dict, fields=None, conditions=None, expires_in=3600, region_name=None):
if (fields is None): fields = {} if (conditions is None): conditions = [] policy = {} datetime_now = datetime.datetime.utcnow() expire_date = (datetime_now + datetime.timedelta(seconds=expires_in)) policy['expiration'] = expire_date.strftime(botocore.auth.ISO8601) policy['con...
'Note that the WaiterModel takes ownership of the waiter_config. It may or may not mutate the waiter_config. If this is a concern, it is best to make a copy of the waiter config before passing it to the WaiterModel. :type waiter_config: dict :param waiter_config: The loaded waiter config from the <service>*.waiters.js...
def __init__(self, waiter_config):
self._waiter_config = waiter_config['waiters'] version = waiter_config.get('version', 'unknown') self._verify_supported_version(version) self.version = version self.waiter_names = list(sorted(waiter_config['waiters'].keys()))
':type name: string :param name: The name of the waiter :type config: botocore.waiter.SingleWaiterConfig :param config: The configuration for the waiter. :type operation_method: callable :param operation_method: A callable that accepts **kwargs and returns a response. For example, this can be a method from a botocore ...
def __init__(self, name, config, operation_method):
self._operation_method = operation_method self.name = name self.config = config
'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...
'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 try: try: if (amt is None): data = self._fp.read() flush_decoder = True else: ...
'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 (self._original_response._method.upper() == 'HEAD')): self._original_response.close() ...
'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