desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Creates middleware Use this like:: @wsgify.middleware def restrict_ip(app, req, ips): if req.remote_addr not in ips: raise webob.exc.HTTPForbidden(\'Bad IP: %s\' % req.remote_addr) return app @wsgify def app(req): return \'hi\' wrapped = restrict_ip(app, ips=[\'127.0.0.1\']) Or if you want to write output-rewriting mi...
@classmethod def middleware(cls, middle_func=None, app=None, **kw):
if (middle_func is None): return _UnboundMiddleware(cls, app, kw) if (app is None): return _MiddlewareFactory(cls, middle_func, kw) return cls(middle_func, middleware_wraps=app, kwargs=kw)
'Input stream of the request (wsgi.input). Setting this property resets the content_length and seekable flag (unlike setting req.body_file_raw).'
def _body_file__get(self):
if (not self.is_body_readable): return StringIO('') r = self.body_file_raw clen = self.content_length if ((not self.is_body_seekable) and (clen is not None)): env = self.environ (wrapped, raw) = env.get('webob._body_file', (0, 0)) if (raw is not r): wrapped = ...
'Get the body of the request (wsgi.input) as a seekable file-like object. Middleware and routing applications should use this attribute over .body_file. If you access this value, CONTENT_LENGTH will also be updated.'
@property def body_file_seekable(self):
if (not self.is_body_seekable): self.make_body_seekable() return self.body_file_raw
'Return the content type, but leaving off any parameters (like charset, but also things like the type in ``application/atom+xml; type=entry``) If you set this property, you can include parameters, or if you don\'t include any parameters in the value then existing parameters will be preserved.'
def _content_type__get(self):
return self.environ.get('CONTENT_TYPE', '').split(';', 1)[0]
'Get the charset of the request. If the request was sent with a charset parameter on the Content-Type, that will be used. Otherwise if there is a default charset (set during construction, or as a class attribute) that will be returned. Otherwise None. Setting this property after request instantiation will always upda...
def _charset__get(self):
content_type = self.environ.get('CONTENT_TYPE', '') (cached_ctype, cached_charset) = self._charset_cache if (cached_ctype == content_type): return cached_charset charset_match = CHARSET_RE.search(content_type) if charset_match: result = charset_match.group(1).strip('"').strip() e...
'All the request headers as a case-insensitive dictionary-like object.'
def _headers__get(self):
if (self._headers is None): self._headers = EnvironHeaders(self.environ) return self._headers
'The URL through the host (no path)'
@property def host_url(self):
e = self.environ url = (self.scheme + '://') if e.get('HTTP_HOST'): host = e['HTTP_HOST'] if (':' in host): (host, port) = host.split(':', 1) else: port = None else: host = e['SERVER_NAME'] port = e['SERVER_PORT'] if (self.scheme == 'ht...
'The URL including SCRIPT_NAME (no PATH_INFO or query string)'
@property def application_url(self):
return (self.host_url + urllib.quote(self.environ.get('SCRIPT_NAME', ''), PATH_SAFE))
'The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING'
@property def path_url(self):
return (self.application_url + urllib.quote(self.environ.get('PATH_INFO', ''), PATH_SAFE))
'The path of the request, without host or query string'
@property def path(self):
return (urllib.quote(self.script_name, PATH_SAFE) + urllib.quote(self.path_info, PATH_SAFE))
'The path of the request, without host but with query string'
@property def path_qs(self):
path = self.path qs = self.environ.get('QUERY_STRING') if qs: path += ('?' + qs) return path
'The full request URL, including QUERY_STRING'
@property def url(self):
url = self.path_url if self.environ.get('QUERY_STRING'): url += ('?' + self.environ['QUERY_STRING']) return url
'Resolve other_url relative to the request URL. If ``to_application`` is True, then resolve it relative to the URL with only SCRIPT_NAME'
def relative_url(self, other_url, to_application=False):
if to_application: url = self.application_url if (not url.endswith('/')): url += '/' else: url = self.path_url return urlparse.urljoin(url, other_url)
'\'Pops\' off the next segment of PATH_INFO, pushing it onto SCRIPT_NAME, and returning the popped segment. Returns None if there is nothing left on PATH_INFO. Does not return ``\'\'`` when there\'s an empty segment (like ``/path//path``); these segments are just ignored. Optional ``pattern`` argument is a regexp to m...
def path_info_pop(self, pattern=None):
path = self.path_info if (not path): return None slashes = '' while path.startswith('/'): slashes += '/' path = path[1:] idx = path.find('/') if (idx == (-1)): idx = len(path) r = path[:idx] if ((pattern is None) or re.match(pattern, r)): self.scri...
'Returns the next segment on PATH_INFO, or None if there is no next segment. Doesn\'t modify the environment.'
def path_info_peek(self):
path = self.path_info if (not path): return None path = path.lstrip('/') return path.split('/', 1)[0]
'Return any *named* variables matched in the URL. Takes values from ``environ[\'wsgiorg.routing_args\']``. Systems like ``routes`` set this value.'
def _urlvars__get(self):
if ('paste.urlvars' in self.environ): return self.environ['paste.urlvars'] elif ('wsgiorg.routing_args' in self.environ): return self.environ['wsgiorg.routing_args'][1] else: result = {} self.environ['wsgiorg.routing_args'] = ((), result) return result
'Return any *positional* variables matched in the URL. Takes values from ``environ[\'wsgiorg.routing_args\']``. Systems like ``routes`` set this value.'
def _urlargs__get(self):
if ('wsgiorg.routing_args' in self.environ): return self.environ['wsgiorg.routing_args'][0] else: return ()
'Is X-Requested-With header present and equal to ``XMLHttpRequest``? Note: this isn\'t set by every XMLHttpRequest request, it is only set if you are using a Javascript library that sets it (or you set the header yourself manually). Currently Prototype and jQuery are known to set this header.'
@property def is_xhr(self):
return (self.environ.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest')
'Host name provided in HTTP_HOST, with fall-back to SERVER_NAME'
def _host__get(self):
if ('HTTP_HOST' in self.environ): return self.environ['HTTP_HOST'] else: return ('%(SERVER_NAME)s:%(SERVER_PORT)s' % self.environ)
'Return the content of the request body.'
def _body__get(self):
if (not self.is_body_readable): return '' self.make_body_seekable() r = self.body_file.read(self.content_length) self.body_file.seek(0) return r
'Return a MultiDict containing all the variables from a form request. Returns an empty dict-like object for non-form requests. Form requests are typically POST requests, however PUT requests with an appropriate Content-Type are also supported.'
@property def str_POST(self):
warn_str_deprecation() return self._str_POST
'Like ``.str_POST``, but decodes values and keys'
@property def POST(self):
vars = self._str_POST vars = UnicodeMultiDict(vars, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return vars
'Return a MultiDict containing all the variables from the QUERY_STRING.'
@property def str_GET(self):
warn_str_deprecation() return self._str_GET
'Like ``.str_GET``, but decodes values and keys'
@property def GET(self):
vars = self._str_GET vars = UnicodeMultiDict(vars, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return vars
'A dictionary-like object containing both the parameters from the query string and request body.'
@property def str_params(self):
warn_str_deprecation() return NestedMultiDict(self._str_GET, self._str_POST)
'Like ``.str_params``, but decodes values and keys'
@property def params(self):
params = NestedMultiDict(self._str_GET, self._str_POST) params = UnicodeMultiDict(params, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return params
'Return a *plain* dictionary of cookies as found in the request.'
@property def str_cookies(self):
warn_str_deprecation() return self._str_cookies
'Like ``.str_cookies``, but decodes values and keys'
@property def cookies(self):
vars = self._str_cookies vars = UnicodeMultiDict(vars, encoding=self.charset, errors=self.unicode_errors, decode_keys=self.decode_param_names) return vars
'Copy the request and environment object. This only does a shallow copy, except of wsgi.input'
def copy(self):
self.make_body_seekable() env = self.environ.copy() new_req = self.__class__(env) new_req.copy_body() return new_req
'Copies the request and environment object, but turning this request into a GET along the way. If this was a POST request (or any other verb) then it becomes GET, and the request body is thrown away.'
def copy_get(self):
env = self.environ.copy() return self.__class__(env, method='GET', content_type=None, body='')
'webob.is_body_readable is a flag that tells us that we can read the input stream even though CONTENT_LENGTH is missing. This allows FakeCGIBody to work and can be used by servers to support chunked encoding in requests. For background see https://bitbucket.org/ianb/webob/issue/6'
def _is_body_readable__get(self):
if http_method_probably_has_body.get(self.method): return True elif (self.content_length is not None): return True else: return self.environ.get('webob.is_body_readable', False)
'This forces ``environ[\'wsgi.input\']`` to be seekable. That means that, the content is copied into a StringIO or temporary file and flagged as seekable, so that it will not be unnecessarily copied again. After calling this method the .body_file is always seeked to the start of file and .content_length is not None. Th...
def make_body_seekable(self):
if self.is_body_seekable: self.body_file_raw.seek(0) else: self.copy_body()
'Copies the body, in cases where it might be shared with another request object and that is not desired. This copies the body in-place, either into a StringIO object or a temporary file.'
def copy_body(self):
if (not self.is_body_readable): self.body = '' elif (self.content_length is None): self.body = self.body_file_raw.read() self._copy_body_tempfile() else: did_copy = self._copy_body_tempfile() if (not did_copy): self.body = self.body_file.read(self.content_...
'Copy wsgi.input to tempfile if necessary. Returns True if it did.'
def _copy_body_tempfile(self):
tempfile_limit = self.request_body_tempfile_limit todo = self.content_length assert isinstance(todo, (int, long)), `todo` if ((not tempfile_limit) or (todo <= tempfile_limit)): return False fileobj = self.make_tempfile() input = self.body_file while (todo > 0): data = input.r...
'Create a tempfile to store big request body. This API is not stable yet. A \'size\' argument might be added.'
def make_tempfile(self):
return tempfile.TemporaryFile()
'Remove headers that make the request conditional. These headers can cause the response to be 304 Not Modified, which in some cases you may not want to be possible. This does not remove headers like If-Match, which are used for conflict detection.'
def remove_conditional_headers(self, remove_encoding=True, remove_range=True, remove_match=True, remove_modified=True):
check_keys = [] if remove_range: check_keys += ['HTTP_IF_RANGE', 'HTTP_RANGE'] if remove_match: check_keys.append('HTTP_IF_NONE_MATCH') if remove_modified: check_keys.append('HTTP_IF_MODIFIED_SINCE') if remove_encoding: check_keys.append('HTTP_ACCEPT_ENCODING') fo...
'Get/set/modify the Cache-Control header (`HTTP spec section 14.9 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)'
def _cache_control__get(self):
env = self.environ value = env.get('HTTP_CACHE_CONTROL', '') (cache_header, cache_obj) = env.get('webob._cache_control', (None, None)) if ((cache_obj is not None) and (cache_header == value)): return cache_obj cache_obj = CacheControl.parse(value, updates_to=self._update_cache_control, type=...
'Return HTTP string representing this request. If skip_body is True, exclude the body. If skip_body is an integer larger than one, skip body only if its length is bigger than that number.'
def as_string(self, skip_body=False):
url = self.url host = self.host_url assert url.startswith(host) url = url[len(host):] parts = [('%s %s %s' % (self.method, url, self.http_version))] body = None if (self.method in ('PUT', 'POST')): if (skip_body > 1): if (len(self.body) > skip_body): ...
'Create a request from HTTP string. If the string contains extra data after the request, raise a ValueError.'
@classmethod def from_string(cls, s):
f = StringIO(s) r = cls.from_file(f) if (f.tell() != len(s)): raise ValueError('The string contains more data than expected') return r
'Read a request from a file-like object (it must implement ``.read(size)`` and ``.readline()``). It will read up to the end of the request, not the end of the file (unless the request is a POST or PUT and has no Content-Length, in that case, the entire file is read). This reads the request as represented by ``str(req)`...
@classmethod def from_file(cls, fp):
start_line = fp.readline() try: (method, resource, http_version) = start_line.rstrip('\r\n').split(None, 2) except ValueError: raise ValueError(('Bad HTTP request line: %r' % start_line)) r = cls(environ_from_url(resource), http_version=http_version, method=method.upper()) ...
'Call the given WSGI application, returning ``(status_string, headerlist, app_iter)`` Be sure to call ``app_iter.close()`` if it\'s there. If catch_exc_info is true, then returns ``(status_string, headerlist, app_iter, exc_info)``, where the fourth item may be None, but won\'t be if there was an exception. If you don\...
def call_application(self, application, catch_exc_info=False):
if self.is_body_seekable: self.body_file_raw.seek(0) captured = [] output = [] def start_response(status, headers, exc_info=None): if ((exc_info is not None) and (not catch_exc_info)): raise exc_info[0], exc_info[1], exc_info[2] captured[:] = [status, headers, exc_inf...
'Like ``.call_application(application)``, except returns a response object with ``.status``, ``.headers``, and ``.body`` attributes. This will use ``self.ResponseClass`` to figure out the class of the response object to return.'
def get_response(self, application, catch_exc_info=False):
if catch_exc_info: (status, headers, app_iter, exc_info) = self.call_application(application, catch_exc_info=True) del exc_info else: (status, headers, app_iter) = self.call_application(application, catch_exc_info=False) return self.ResponseClass(status=status, headerlist=list(header...
'Create a blank request environ (and Request wrapper) with the given path (path should be urlencoded), and any keys from environ. The path will become path_info, with any query string split off and used. All necessary keys will be added to the environ, but the values you pass in will take precedence. If you pass in ba...
@classmethod def blank(cls, path, environ=None, base_url=None, headers=None, POST=None, **kw):
env = environ_from_url(path) if base_url: (scheme, netloc, path, query, fragment) = urlparse.urlsplit(base_url) if (query or fragment): raise ValueError(('base_url (%r) cannot have a query or fragment' % base_url)) if scheme: env['wsgi.url_sch...
'Return the longhand version of the IP address as a string.'
@property def exploded(self):
return self._explode_shorthand_ip_string()
'Return the shorthand version of the IP address as a string.'
@property def compressed(self):
return str(self)
'Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn\'t return the network or broadcast addresses.'
def iterhosts(self):
cur = (int(self.network) + 1) bcast = (int(self.broadcast) - 1) while (cur <= bcast): cur += 1 (yield IPAddress((cur - 1), version=self._version))
'Tell if self is partly contained in other.'
def overlaps(self, other):
return ((self.network in other) or (self.broadcast in other) or ((other.network in self) or (other.broadcast in self)))
'Number of hosts in the current subnet.'
@property def numhosts(self):
return ((int(self.broadcast) - int(self.network)) + 1)
'Remove an address from a larger block. For example: addr1 = IPNetwork(\'10.1.1.0/24\') addr2 = IPNetwork(\'10.1.1.0/26\') addr1.address_exclude(addr2) = [IPNetwork(\'10.1.1.64/26\'), IPNetwork(\'10.1.1.128/25\')] or IPv6: addr1 = IPNetwork(\'::1/32\') addr2 = IPNetwork(\'::1/128\') addr1.address_exclude(addr2) = [IPNe...
def address_exclude(self, other):
if (not (self._version == other._version)): raise TypeError(('%s and %s are not of the same version' % (str(self), str(other)))) if (not isinstance(other, _BaseNet)): raise TypeError(('%s is not a network object' % str(other))) if (other not in self): ...
'Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren\'t considered at all in this method. If you want to compare host bits, you can easily enough do a \'HostA._ip < HostB._ip\' Args: other: An IP object. Returns...
def compare_networks(self, other):
if (self._version < other._version): return (-1) if (self._version > other._version): return 1 if (self.network < other.network): return (-1) if (self.network > other.network): return 1 if (self.netmask < other.netmask): return (-1) if (self.netmask > othe...
'Network-only key function. Returns an object that identifies this address\' network and netmask. This function is a suitable "key" argument for sorted() and list.sort().'
def _get_networks_key(self):
return (self._version, self.network, self.netmask)
'Turn the prefix length netmask into a int for comparison. Args: prefixlen: An integer, the prefix length. Returns: An integer.'
def _ip_int_from_prefix(self, prefixlen=None):
if ((not prefixlen) and (prefixlen != 0)): prefixlen = self._prefixlen return (self._ALL_ONES ^ (self._ALL_ONES >> prefixlen))
'Return prefix length from the decimal netmask. Args: ip_int: An integer, the IP address. mask: The netmask. Defaults to 32. Returns: An integer, the prefix length.'
def _prefix_from_ip_int(self, ip_int, mask=32):
while mask: if ((ip_int & 1) == 1): break ip_int >>= 1 mask -= 1 return mask
'Turn a prefix length into a dotted decimal string. Args: prefixlen: An integer, the netmask prefix length. Returns: A string, the dotted decimal netmask string.'
def _ip_string_from_prefix(self, prefixlen=None):
if (not prefixlen): prefixlen = self._prefixlen return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
'The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), return a list with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix...
def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == self._max_prefixlen): (yield self) return if (new_prefix is not None): if (new_prefix < self._prefixlen): raise ValueError('new prefix must be longer') if (prefixlen_diff != 1): raise ValueError('cannot set prefixle...
'Return the network object with the host bits masked out.'
def masked(self):
return IPNetwork(('%s/%d' % (self.network, self._prefixlen)), version=self._version)
'Return a list of subnets, rather than an iterator.'
def subnet(self, prefixlen_diff=1, new_prefix=None):
return list(self.iter_subnets(prefixlen_diff, new_prefix))
'The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixl...
def supernet(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == 0): return self if (new_prefix is not None): if (new_prefix > self._prefixlen): raise ValueError('new prefix must be shorter') if (prefixlen_diff != 1): raise ValueError('cannot set prefixlen_diff and new_prefix') ...
'Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn\'t a valid IPv4 Address.'
def _ip_int_from_string(self, ip_str):
octets = ip_str.split('.') if (len(octets) != 4): raise AddressValueError(ip_str) packed_ip = 0 for oc in octets: try: packed_ip = ((packed_ip << 8) | self._parse_octet(oc)) except ValueError: raise AddressValueError(ip_str) return packed_ip
'Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn\'t strictly a decimal from [0..255].'
def _parse_octet(self, octet_str):
if (not self._DECIMAL_DIGITS.issuperset(octet_str)): raise ValueError octet_int = int(octet_str, 10) if ((octet_int > 255) or ((octet_str[0] == '0') and (len(octet_str) > 1))): raise ValueError return octet_int
'Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.'
def _string_from_ip_int(self, ip_int):
octets = [] for _ in xrange(4): octets.insert(0, str((ip_int & 255))) ip_int >>= 8 return '.'.join(octets)
'The binary representation of this address.'
@property def packed(self):
return v4_int_to_packed(self._ip)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range.'
@property def is_reserved(self):
return (self in IPv4Network('240.0.0.0/4'))
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918.'
@property def is_private(self):
return ((self in IPv4Network('10.0.0.0/8')) or (self in IPv4Network('172.16.0.0/12')) or (self in IPv4Network('192.168.0.0/16')))
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details.'
@property def is_multicast(self):
return (self in IPv4Network('224.0.0.0/4'))
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3.'
@property def is_unspecified(self):
return (self in IPv4Network('0.0.0.0'))
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330.'
@property def is_loopback(self):
return (self in IPv4Network('127.0.0.0/8'))
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927.'
@property def is_link_local(self):
return (self in IPv4Network('169.254.0.0/16'))
'Args: address: A string or integer representing the IP \'192.168.1.1\' Additionally, an integer can be passed, so IPv4Address(\'192.168.1.1\') == IPv4Address(3232235777). or, more generally IPv4Address(int(IPv4Address(\'192.168.1.1\'))) == IPv4Address(\'192.168.1.1\') Raises: AddressValueError: If ipaddr isn\'t a vali...
def __init__(self, address):
_BaseV4.__init__(self, address) if isinstance(address, (int, long)): self._ip = address if ((address < 0) or (address > self._ALL_ONES)): raise AddressValueError(address) return if isinstance(address, Bytes): try: (self._ip,) = struct.unpack('!I', addr...
'Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. \'192.168.1.1/24\' \'192.168.1.1/255.255.255.0\' \'192.168.1.1/0.0.0.255\' are all functionally the same in IPv4. Similarly, \'192.168.1.1\' \'192.168.1.1/255.255.255.255\' \'192.168.1.1/32\' are also functionaly...
def __init__(self, address, strict=False):
_BaseNet.__init__(self, address) _BaseV4.__init__(self, address) if isinstance(address, (int, long, Bytes)): self.ip = IPv4Address(address) self._ip = self.ip._ip self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) return addr = str(ad...
'Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask.'
def _is_hostmask(self, ip_str):
bits = ip_str.split('.') try: parts = [int(x) for x in bits if (int(x) in self._valid_mask_octets)] except ValueError: return False if (len(parts) != len(bits)): return False if (parts[0] < parts[(-1)]): return True return False
'Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask.'
def _is_valid_netmask(self, netmask):
mask = netmask.split('.') if (len(mask) == 4): if [x for x in mask if (int(x) not in self._valid_mask_octets)]: return False if [y for (idx, y) in enumerate(mask) if ((idx > 0) and (y > mask[(idx - 1)]))]: return False return True try: netmask = int(ne...
'Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: A long, the IPv6 ip_str. Raises: AddressValueError: if ip_str isn\'t a valid IPv6 Address.'
def _ip_int_from_string(self, ip_str):
parts = ip_str.split(':') if (len(parts) < 3): raise AddressValueError(ip_str) if ('.' in parts[(-1)]): ipv4_int = IPv4Address(parts.pop())._ip parts.append(('%x' % ((ipv4_int >> 16) & 65535))) parts.append(('%x' % (ipv4_int & 65535))) if (len(parts) > (self._HEXTET_COUNT...
'Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn\'t strictly a hex number from [0..FFFF].'
def _parse_hextet(self, hextet_str):
if (not self._HEX_DIGITS.issuperset(hextet_str)): raise ValueError hextet_int = int(hextet_str, 16) if (hextet_int > 65535): raise ValueError return hextet_int
'Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets:...
def _compress_hextets(self, hextets):
best_doublecolon_start = (-1) best_doublecolon_len = 0 doublecolon_start = (-1) doublecolon_len = 0 for index in range(len(hextets)): if (hextets[index] == '0'): doublecolon_len += 1 if (doublecolon_start == (-1)): doublecolon_start = index ...
'Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones.'
def _string_from_ip_int(self, ip_int=None):
if ((not ip_int) and (ip_int != 0)): ip_int = int(self._ip) if (ip_int > self._ALL_ONES): raise ValueError('IPv6 address is too large') hex_str = ('%032x' % ip_int) hextets = [] for x in range(0, 32, 4): hextets.append(('%x' % int(hex_str[x:(x + 4)], 16))) hex...
'Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.'
def _explode_shorthand_ip_string(self):
if isinstance(self, _BaseNet): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) parts = [] for i in xrange(self._HEXTET_COUNT): parts.append(('%04x' % (ip_int & 65535))) ip_int >>= 16 parts.reverse() if isinstance(self, ...
'The binary representation of this address.'
@property def packed(self):
return v6_int_to_packed(self._ip)
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.'
@property def is_multicast(self):
return (self in IPv6Network('ff00::/8'))
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.'
@property def is_reserved(self):
return ((self in IPv6Network('::/8')) or (self in IPv6Network('100::/8')) or (self in IPv6Network('200::/7')) or (self in IPv6Network('400::/6')) or (self in IPv6Network('800::/5')) or (self in IPv6Network('1000::/4')) or (self in IPv6Network('4000::/3')) or (self in IPv6Network('6000::/3')) or (self in IPv6Network...
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.'
@property def is_unspecified(self):
return ((self._ip == 0) and (getattr(self, '_prefixlen', 128) == 128))
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3.'
@property def is_loopback(self):
return ((self._ip == 1) and (getattr(self, '_prefixlen', 128) == 128))
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291.'
@property def is_link_local(self):
return (self in IPv6Network('fe80::/10'))
'Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6.'
@property def is_site_local(self):
return (self in IPv6Network('fec0::/10'))
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 4193.'
@property def is_private(self):
return (self in IPv6Network('fc00::/7'))
'Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise.'
@property def ipv4_mapped(self):
if ((self._ip >> 32) != 65535): return None return IPv4Address((self._ip & 4294967295))
'Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn\'t appear to be a teredo address (doesn\'t start with 2001::/32)'
@property def teredo(self):
if ((self._ip >> 96) != 536936448): return None return (IPv4Address(((self._ip >> 64) & 4294967295)), IPv4Address(((~ self._ip) & 4294967295)))
'Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn\'t appear to contain a 6to4 embedded address.'
@property def sixtofour(self):
if ((self._ip >> 112) != 8194): return None return IPv4Address(((self._ip >> 80) & 4294967295))
'Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address(\'2001:4860::\') == IPv6Address(42541956101370907050197289607612071936L). or, more generally IPv6Address(IPv6Address(\'2001:4860::\')._ip) == IPv6Address(\'2001:4860::\')...
def __init__(self, address):
_BaseV6.__init__(self, address) if isinstance(address, (int, long)): self._ip = address if ((address < 0) or (address > self._ALL_ONES)): raise AddressValueError(address) return if isinstance(address, Bytes): try: (hi, lo) = struct.unpack('!QQ', addres...
'Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. \'2001:4860::/128\' \'2001:4860:0000:0000:0000:0000:0000:0000/128\' \'2001:4860::\' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create a...
def __init__(self, address, strict=False):
_BaseNet.__init__(self, address) _BaseV6.__init__(self, address) if isinstance(address, (int, long, Bytes)): self.ip = IPv6Address(address) self._ip = self.ip._ip self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return addr = str(ad...
'Verify that the netmask/prefixlen is valid. Args: prefixlen: A string, the netmask in prefix length format. Returns: A boolean, True if the prefix represents a valid IPv6 netmask.'
def _is_valid_netmask(self, prefixlen):
try: prefixlen = int(prefixlen) except ValueError: return False return (0 <= prefixlen <= self._max_prefixlen)
'@see: #799'
def test_read_negative(self):
x = util.BufferedByteStream() x.write(('*' * 6000)) x.seek(100) self.assertRaises(IOError, x.read, (-345))
'Test L{util.BufferedByteStream.append} with C{str} objects.'
def test_append_string(self):
a = util.BufferedByteStream() self.assertEqual(a.getvalue(), '') self.assertEqual(a.tell(), 0) self.assertEqual(len(a), 0) a.append('foo') self.assertEqual(a.getvalue(), 'foo') self.assertEqual(a.tell(), 0) self.assertEqual(len(a), 3) a = util.BufferedByteStream('bar') self.asser...
'Test L{util.BufferedByteStream.append} with C{unicode} objects.'
def test_append_unicode(self):
a = util.BufferedByteStream() self.assertEqual(a.getvalue(), '') self.assertEqual(a.tell(), 0) self.assertEqual(len(a), 0) a.append(u'foo') self.assertEqual(a.getvalue(), 'foo') self.assertEqual(a.tell(), 0) self.assertEqual(len(a), 3) a = util.BufferedByteStream('bar') self.asse...
'Test for initial deferred compliation'
def test_init_deferred(self):
x = ClassAlias(Spam, defer=True) self.assertTrue(x.anonymous) self.assertEqual(x.dynamic, None) self.assertFalse(x.amf3) self.assertFalse(x.external) self.assertEqual(x.readonly_attrs, None) self.assertEqual(x.static_attrs, None) self.assertEqual(x.exclude_attrs, None) self.assertEqu...
'Tests for `getSmallMessage`'
def test_getmessage(self):
for cls in ['AbstractMessage', 'ErrorMessage', 'RemotingMessage']: cls = getattr(messaging, cls) self.assertRaises(NotImplementedError, cls().getSmallMessage) kwargs = {'body': {'foo': 'bar'}, 'clientId': 'spam', 'destination': 'eggs', 'headers': {'blarg': 'whoop'}, 'messageId': 'baz', 'timestam...
'See #727'
def test_error_unicode_message(self):
def echo(x): raise TypeError(u'\u0192\xf8\xf8') gw = gateway.BaseGateway({'echo': echo}) rp = amf3.RequestProcessor(gw) message = messaging.RemotingMessage(body=['spam.eggs'], operation='echo') request = remoting.Request('null', body=[message]) response = rp(request) ack = response.b...
'Tests the AMF client version.'
def test_client_version(self):
for x in ('\x00', '\x01', '\x03'): try: remoting.decode(('\x00' + x)) except IOError: pass
'Test header decoder.'
def test_simple_header(self):
msg = remoting.decode('\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x05\n\x00\x00\x00\x00\x00\x00') self.assertEqual(msg.amfVersion, 0) self.assertEqual(len(msg.headers), 1) self.assertEqual(('name' in msg.headers), True) self.assertEqual(msg.headers['name'], []) self.assertFalse(msg.headers.is_...
'Ensure that the timezone offsets work as expected'
def test_timezone(self):
import datetime td = datetime.timedelta(hours=(-5)) msg = remoting.decode('\x00\x00\x00\x00\x00\x01\x00\x0b/1/onResult\x00\x04null\x00\x00\x00\x00\n\x00\x00\x00\x01\x0bBr>\xcc\n~\x00\x00\x00\x00', timezone_offset=td) self.assertEqual(msg['/1'].body[0], datetime.datetime(2009, 9, 24, 10, 52, 12))