code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
result = []
frames = sorted(self.items)
for idx, frame in enumerate(frames[:-1]):
next_frame = frames[idx + 1]
if next_frame - frame != 1:
r = xrange(frame + 1, next_frame)
# Check if the next update to the result set
# will exceed out max frame size.
# Prevent memory overflows.
self._maxSizeCheck(len(r) + len(result))
result += r
if not result:
return ''
return FrameSet.framesToFrameRange(
result, zfill=zfill, sort=False, compress=False) | def invertedFrameRange(self, zfill=0) | Return the inverse of the :class:`FrameSet` 's frame range, padded if
desired.
The inverse is every frame within the full extent of the range.
Examples:
>>> FrameSet('1-100x2').invertedFrameRange()
'2-98x2'
>>> FrameSet('1-100x2').invertedFrameRange(5)
'00002-00098x2'
If the inverted frame size exceeds `fileseq.constants.MAX_FRAME_SIZE`,
a ``MaxSizeException`` will be raised.
Args:
zfill (int): the width to use to zero-pad the frame range string
Returns:
str:
Raises:
:class:`fileseq.exceptions.MaxSizeException`: | 6.484597 | 6.716742 | 0.965438 |
return FrameSet(FrameSet.framesToFrameRange(
self.items, sort=True, compress=False)) | def normalize(self) | Returns a new normalized (sorted and compacted) :class:`FrameSet`.
Returns:
:class:`FrameSet`: | 34.449371 | 25.591785 | 1.346111 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items.isdisjoint(other.items) | def isdisjoint(self, other) | Check if the contents of :class:self has no common intersection with the
contents of :class:other.
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | 5.333252 | 4.68183 | 1.139138 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items <= other.items | def issubset(self, other) | Check if the contents of `self` is a subset of the contents of
`other.`
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | 7.335958 | 5.88939 | 1.245623 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items >= other.items | def issuperset(self, other) | Check if the contents of `self` is a superset of the contents of
`other.`
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | 7.446269 | 6.271289 | 1.187359 |
from_frozenset = self.items.difference(*map(set, other))
return self.from_iterable(from_frozenset, sort=True) | def difference(self, *other) | Returns a new :class:`FrameSet` with elements in `self` but not in
`other`.
Args:
other (:class:`FrameSet`): or objects that can cast to :class:`FrameSet`
Returns:
:class:`FrameSet`: | 9.49687 | 12.594979 | 0.75402 |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
from_frozenset = self.items.symmetric_difference(other.items)
return self.from_iterable(from_frozenset, sort=True) | def symmetric_difference(self, other) | Returns a new :class:`FrameSet` that contains all the elements in either
`self` or `other`, but not both.
Args:
other (:class:`FrameSet`):
Returns:
:class:`FrameSet`: | 5.825325 | 6.482547 | 0.898617 |
fail = False
size = 0
if isinstance(obj, numbers.Number):
if obj > constants.MAX_FRAME_SIZE:
fail = True
size = obj
elif hasattr(obj, '__len__'):
size = len(obj)
fail = size > constants.MAX_FRAME_SIZE
if fail:
raise MaxSizeException('Frame size %s > %s (MAX_FRAME_SIZE)' \
% (size, constants.MAX_FRAME_SIZE)) | def _maxSizeCheck(cls, obj) | Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE
Args:
obj (numbers.Number or collection):
Raises:
:class:`fileseq.exceptions.MaxSizeException`: | 3.087346 | 2.536744 | 1.217051 |
# we're willing to trim padding characters from consideration
# this translation is orders of magnitude faster than prior method
frange = str(frange).translate(None, ''.join(PAD_MAP.keys()))
if not frange:
return True
for part in frange.split(','):
if not part:
continue
try:
FrameSet._parse_frange_part(part)
except ParseException:
return False
return True | def isFrameRange(frange) | Return True if the given string is a frame range. Any padding
characters, such as '#' and '@' are ignored.
Args:
frange (str): a frame range to test
Returns:
bool: | 8.245572 | 7.980755 | 1.033182 |
def _do_pad(match):
result = list(match.groups())
result[1] = pad(result[1], zfill)
if result[4]:
result[4] = pad(result[4], zfill)
return ''.join((i for i in result if i))
return PAD_RE.sub(_do_pad, frange) | def padFrameRange(frange, zfill) | Return the zero-padded version of the frame range string.
Args:
frange (str): a frame range to test
zfill (int):
Returns:
str: | 3.854896 | 4.372808 | 0.881561 |
match = FRANGE_RE.match(frange)
if not match:
msg = 'Could not parse "{0}": did not match {1}'
raise ParseException(msg.format(frange, FRANGE_RE.pattern))
start, end, modifier, chunk = match.groups()
start = int(start)
end = int(end) if end is not None else start
if end > start and chunk is not None and int(chunk) < 0:
msg = 'Could not parse "{0}: chunk can not be negative'
raise ParseException(msg.format(frange))
chunk = abs(int(chunk)) if chunk is not None else 1
# a zero chunk is just plain illogical
if chunk == 0:
msg = 'Could not parse "{0}": chunk cannot be 0'
raise ParseException(msg.format(frange))
return start, end, modifier, chunk | def _parse_frange_part(frange) | Internal method: parse a discrete frame range part.
Args:
frange (str): single part of a frame range as a string
(ie "1-100x5")
Returns:
tuple: (start, end, modifier, chunk)
Raises:
:class:`.ParseException`: if the frame range can
not be parsed | 2.75964 | 2.492279 | 1.107275 |
if stop is None:
return ''
pad_start = pad(start, zfill)
pad_stop = pad(stop, zfill)
if stride is None or start == stop:
return '{0}'.format(pad_start)
elif abs(stride) == 1:
return '{0}-{1}'.format(pad_start, pad_stop)
else:
return '{0}-{1}x{2}'.format(pad_start, pad_stop, stride) | def _build_frange_part(start, stop, stride, zfill=0) | Private method: builds a proper and padded
frame range string.
Args:
start (int): first frame
stop (int or None): last frame
stride (int or None): increment
zfill (int): width for zero padding
Returns:
str: | 2.294744 | 2.323005 | 0.987834 |
_build = FrameSet._build_frange_part
curr_start = None
curr_stride = None
curr_frame = None
last_frame = None
curr_count = 0
for curr_frame in frames:
if curr_start is None:
curr_start = curr_frame
last_frame = curr_frame
curr_count += 1
continue
if curr_stride is None:
curr_stride = abs(curr_frame-curr_start)
new_stride = abs(curr_frame-last_frame)
if curr_stride == new_stride:
last_frame = curr_frame
curr_count += 1
elif curr_count == 2 and curr_stride != 1:
yield _build(curr_start, curr_start, None, zfill)
curr_start = last_frame
curr_stride = new_stride
last_frame = curr_frame
else:
yield _build(curr_start, last_frame, curr_stride, zfill)
curr_stride = None
curr_start = curr_frame
last_frame = curr_frame
curr_count = 1
if curr_count == 2 and curr_stride != 1:
yield _build(curr_start, curr_start, None, zfill)
yield _build(curr_frame, curr_frame, None, zfill)
else:
yield _build(curr_start, curr_frame, curr_stride, zfill) | def framesToFrameRanges(frames, zfill=0) | Converts a sequence of frames to a series of padded
frame range strings.
Args:
frames (collections.Iterable): sequence of frames to process
zfill (int): width for zero padding
Yields:
str: | 2.064047 | 2.156772 | 0.957008 |
if compress:
frames = unique(set(), frames)
frames = list(frames)
if not frames:
return ''
if len(frames) == 1:
return pad(frames[0], zfill)
if sort:
frames.sort()
return ','.join(FrameSet.framesToFrameRanges(frames, zfill)) | def framesToFrameRange(frames, sort=True, zfill=0, compress=False) | Converts an iterator of frames into a
frame range string.
Args:
frames (collections.Iterable): sequence of frames to process
sort (bool): sort the sequence before processing
zfill (int): width for zero padding
compress (bool): remove any duplicates before processing
Returns:
str: | 3.748139 | 4.254684 | 0.880944 |
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 1.0/a parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param header_auth: Authentication via header, defaults to `False.`
:type header_auth: bool
:param realm: The auth header realm, defaults to ``""``.
:type realm: str
:param \*\*req_kwargs: Keyworded args to be passed down to Requests.
:type \*\*req_kwargs: dict
'''
req_kwargs.setdefault('headers', {})
req_kwargs['headers'] = CaseInsensitiveDict(req_kwargs['headers'])
url = self._set_url(url)
entity_method = method.upper() in ENTITY_METHODS
if entity_method and not req_kwargs.get('files', None):
req_kwargs['headers'].setdefault('Content-Type', FORM_URLENCODED)
form_urlencoded = \
req_kwargs['headers'].get('Content-Type') == FORM_URLENCODED
# inline string conversion
if is_basestring(req_kwargs.get('params')):
req_kwargs['params'] = dict(parse_qsl(req_kwargs['params']))
if is_basestring(req_kwargs.get('data')) and form_urlencoded:
req_kwargs['data'] = dict(parse_qsl(req_kwargs['data']))
req_kwargs.setdefault('timeout', OAUTH1_DEFAULT_TIMEOUT)
oauth_params = self._get_oauth_params(req_kwargs)
# ensure we always create new instances of dictionary elements
for key, value in req_kwargs.items():
if isinstance(value, dict):
req_kwargs[key] = deepcopy(value)
# sign the request
oauth_params['oauth_signature'] = \
self.signature.sign(self.consumer_secret,
self.access_token_secret,
method,
url,
oauth_params,
req_kwargs)
if header_auth and 'oauth_signature' not in \
req_kwargs['headers'].get('Authorization', ''):
req_kwargs['auth'] = OAuth1Auth(oauth_params, realm)
elif entity_method and 'oauth_signature' not in \
(req_kwargs.get('data') or {}):
req_kwargs['data'] = req_kwargs.get('data') or {}
# If we have a urlencoded entity-body we should pass the OAuth
# parameters on this body. However, if we do not, then we need to
# pass these over the request URI, i.e. on params.
#
# See:
#
# http://tools.ietf.org/html/rfc5849#section-3.5.2
#
# and:
#
# http://tools.ietf.org/html/rfc5849#section-3.5.3
if form_urlencoded:
req_kwargs['data'].update(oauth_params)
else:
req_kwargs.setdefault('params', {})
req_kwargs['params'].update(oauth_params)
elif 'oauth_signature' not in url:
req_kwargs.setdefault('params', {})
req_kwargs['params'].update(oauth_params)
return super(OAuth1Session, self).request(method, url, **req_kwargs) | def request(self,
method,
url,
header_auth=False,
realm='',
**req_kwargs) | A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 1.0/a parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param header_auth: Authentication via header, defaults to `False.`
:type header_auth: bool
:param realm: The auth header realm, defaults to ``""``.
:type realm: str
:param \*\*req_kwargs: Keyworded args to be passed down to Requests.
:type \*\*req_kwargs: dict | 2.730322 | 2.176476 | 1.254469 |
'''
Parses and sets optional OAuth parameters on a request.
:param oauth_param: The OAuth parameter to parse.
:type oauth_param: str
:param req_kwargs: The keyworded arguments passed to the request
method.
:type req_kwargs: dict
'''
params = req_kwargs.get('params', {})
data = req_kwargs.get('data') or {}
for oauth_param in OPTIONAL_OAUTH_PARAMS:
if oauth_param in params:
oauth_params[oauth_param] = params.pop(oauth_param)
if oauth_param in data:
oauth_params[oauth_param] = data.pop(oauth_param)
if params:
req_kwargs['params'] = params
if data:
req_kwargs['data'] = data | def _parse_optional_params(self, oauth_params, req_kwargs) | Parses and sets optional OAuth parameters on a request.
:param oauth_param: The OAuth parameter to parse.
:type oauth_param: str
:param req_kwargs: The keyworded arguments passed to the request
method.
:type req_kwargs: dict | 2.392434 | 1.728172 | 1.384373 |
'''Prepares OAuth params for signing.'''
oauth_params = {}
oauth_params['oauth_consumer_key'] = self.consumer_key
oauth_params['oauth_nonce'] = sha1(
str(random()).encode('ascii')).hexdigest()
oauth_params['oauth_signature_method'] = self.signature.NAME
oauth_params['oauth_timestamp'] = int(time())
if self.access_token is not None:
oauth_params['oauth_token'] = self.access_token
oauth_params['oauth_version'] = self.VERSION
self._parse_optional_params(oauth_params, req_kwargs)
return oauth_params | def _get_oauth_params(self, req_kwargs) | Prepares OAuth params for signing. | 2.36685 | 2.229189 | 1.061754 |
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 2.0 parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param bearer_auth: Whether to use Bearer Authentication or not,
defaults to `True`.
:type bearer_auth: bool
:param \*\*req_kwargs: Keyworded args to be passed down to Requests.
:type \*\*req_kwargs: dict
'''
req_kwargs.setdefault('params', {})
url = self._set_url(url)
if is_basestring(req_kwargs['params']):
req_kwargs['params'] = dict(parse_qsl(req_kwargs['params']))
if bearer_auth and self.access_token is not None:
req_kwargs['auth'] = OAuth2Auth(self.access_token)
else:
req_kwargs['params'].update({self.access_token_key:
self.access_token})
req_kwargs.setdefault('timeout', OAUTH2_DEFAULT_TIMEOUT)
return super(OAuth2Session, self).request(method, url, **req_kwargs) | def request(self, method, url, bearer_auth=True, **req_kwargs) | A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 2.0 parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param bearer_auth: Whether to use Bearer Authentication or not,
defaults to `True`.
:type bearer_auth: bool
:param \*\*req_kwargs: Keyworded args to be passed down to Requests.
:type \*\*req_kwargs: dict | 2.729393 | 1.782732 | 1.531017 |
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects Ofly parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param hash_meth: The hash method to use for signing, defaults to
"sha1".
:type hash_meth: str
:param user_id: The oflyUserid, defaults to `None`.
:type user_id: str
:param \*\*req_kwargs: Keyworded args to be passed down to Requests.
:type \*\*req_kwargs: dict
'''
req_kwargs.setdefault('params', {})
req_kwargs.setdefault('timeout', OFLY_DEFAULT_TIMEOUT)
url = self._set_url(url)
user_id = user_id or self.user_id
assert user_id is not None, \
'An oflyUserid must be provided as `user_id`.'
if is_basestring(req_kwargs['params']):
req_kwargs['params'] = dict(parse_qsl(req_kwargs['params']))
req_kwargs['params'].update({'oflyUserid': user_id})
params = OflySession.sign(url,
self.app_id,
self.app_secret,
hash_meth=hash_meth,
**req_kwargs['params'])
# NOTE: Requests can't seem to handle unicode objects, instead we can
# encode a string here.
req_kwargs['params'] = params
if not isinstance(req_kwargs['params'], bytes):
req_kwargs['params'] = req_kwargs['params'].encode('utf-8')
return super(OflySession, self).request(method, url, **req_kwargs) | def request(self,
method,
url,
user_id=None,
hash_meth='sha1',
**req_kwargs) | A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects Ofly parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param hash_meth: The hash method to use for signing, defaults to
"sha1".
:type hash_meth: str
:param user_id: The oflyUserid, defaults to `None`.
:type user_id: str
:param \*\*req_kwargs: Keyworded args to be passed down to Requests.
:type \*\*req_kwargs: dict | 3.035129 | 1.961114 | 1.547656 |
'''
A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type app_secret: str
:param hash_meth: The hash method to use for signing, defaults to
"sha1".
:type hash_meth: str
:param \*\*params: Additional parameters.
:type \*\*\params: dict
'''
hash_meth_str = hash_meth
if hash_meth == 'sha1':
hash_meth = sha1
elif hash_meth == 'md5':
hash_meth = md5
else:
raise TypeError('hash_meth must be one of "sha1", "md5"')
now = datetime.utcnow()
milliseconds = now.microsecond // 1000
time_format = '%Y-%m-%dT%H:%M:%S.{0}Z'.format(milliseconds)
ofly_params = {'oflyAppId': app_id,
'oflyHashMeth': hash_meth_str.upper(),
'oflyTimestamp': now.strftime(time_format)}
url_path = urlsplit(url).path
signature_base_string = app_secret + url_path + '?'
if len(params):
signature_base_string += get_sorted_params(params) + '&'
signature_base_string += get_sorted_params(ofly_params)
if not isinstance(signature_base_string, bytes):
signature_base_string = signature_base_string.encode('utf-8')
ofly_params['oflyApiSig'] = \
hash_meth(signature_base_string).hexdigest()
all_params = dict(tuple(ofly_params.items()) + tuple(params.items()))
return get_sorted_params(all_params) | def sign(url, app_id, app_secret, hash_meth='sha1', **params) | A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type app_secret: str
:param hash_meth: The hash method to use for signing, defaults to
"sha1".
:type hash_meth: str
:param \*\*params: Additional parameters.
:type \*\*\params: dict | 2.716516 | 1.948139 | 1.394415 |
''' Constructs and returns an authentication header. '''
realm = 'realm="{realm}"'.format(realm=self.realm)
params = ['{k}="{v}"'.format(k=k, v=quote(str(v), safe=''))
for k, v in self.oauth_params.items()]
return 'OAuth ' + ','.join([realm] + params) | def _get_auth_header(self) | Constructs and returns an authentication header. | 3.8901 | 3.445399 | 1.129071 |
'''
Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str
'''
scheme, netloc, path, query, fragment = urlsplit(url)
return urlunsplit((scheme, netloc, path, '', fragment)) | def _remove_qs(self, url) | Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str | 3.709028 | 2.280698 | 1.626269 |
'''
This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if
this is a `POST` or `PUT` request. This ensures the correct header is
set as per spec.
Finally we sort the parameters in preparation for signing and return
a URL encoded string of all normalized parameters.
:param oauth_params: OAuth params to sign with.
:type oauth_params: dict
:param req_kwargs: Request kwargs to normalize.
:type req_kwargs: dict
'''
normalized = []
params = req_kwargs.get('params', {})
data = req_kwargs.get('data', {})
headers = req_kwargs.get('headers', {})
# process request parameters
for k, v in params.items():
if v is not None:
normalized += [(k, v)]
# process request data
if 'Content-Type' in headers and \
headers['Content-Type'] == FORM_URLENCODED:
for k, v in data.items():
normalized += [(k, v)]
# extract values from our list of tuples
all_normalized = []
for t in normalized:
k, v = t
if is_basestring(v) and not isinstance(v, bytes):
v = v.encode('utf-8')
all_normalized += [(k, v)]
# add in the params from oauth_params for signing
for k, v in oauth_params.items():
if (k, v) in all_normalized: # pragma: no cover
continue
all_normalized += [(k, v)]
# sort the params as per the OAuth 1.0/a spec
all_normalized.sort()
# finally encode the params as a string
return urlencode(all_normalized, True)\
.replace('+', '%20')\
.replace('%7E', '~') | def _normalize_request_parameters(self, oauth_params, req_kwargs) | This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if
this is a `POST` or `PUT` request. This ensures the correct header is
set as per spec.
Finally we sort the parameters in preparation for signing and return
a URL encoded string of all normalized parameters.
:param oauth_params: OAuth params to sign with.
:type oauth_params: dict
:param req_kwargs: Request kwargs to normalize.
:type req_kwargs: dict | 3.549323 | 2.049065 | 1.732167 |
'''Sign request parameters.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param url: The URL of this particular request.
:type url: str
:param oauth_params: OAuth parameters.
:type oauth_params: dict
:param req_kwargs: Keyworded args that will be sent to the request
method.
:type req_kwargs: dict
'''
url = self._remove_qs(url)
oauth_params = \
self._normalize_request_parameters(oauth_params, req_kwargs)
parameters = map(self._escape, [method, url, oauth_params])
key = self._escape(consumer_secret) + b'&'
if access_token_secret is not None:
key += self._escape(access_token_secret)
# build a Signature Base String
signature_base_string = b'&'.join(parameters)
# hash the string with HMAC-SHA1
hashed = hmac.new(key, signature_base_string, sha1)
# return the signature
return base64.b64encode(hashed.digest()).decode() | def sign(self,
consumer_secret,
access_token_secret,
method,
url,
oauth_params,
req_kwargs) | Sign request parameters.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param url: The URL of this particular request.
:type url: str
:param oauth_params: OAuth parameters.
:type oauth_params: dict
:param req_kwargs: Keyworded args that will be sent to the request
method.
:type req_kwargs: dict | 2.469459 | 2.068271 | 1.193972 |
'''Sign request parameters.
:param consumer_secret: RSA private key.
:type consumer_secret: str or RSA._RSAobj
:param access_token_secret: Unused.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param url: The URL of this particular request.
:type url: str
:param oauth_params: OAuth parameters.
:type oauth_params: dict
:param req_kwargs: Keyworded args that will be sent to the request
method.
:type req_kwargs: dict
'''
url = self._remove_qs(url)
oauth_params = \
self._normalize_request_parameters(oauth_params, req_kwargs)
parameters = map(self._escape, [method, url, oauth_params])
# build a Signature Base String
signature_base_string = b'&'.join(parameters)
# resolve the key
if is_basestring(consumer_secret):
consumer_secret = self.RSA.importKey(consumer_secret)
if not isinstance(consumer_secret, self.RSA._RSAobj):
raise ValueError('invalid consumer_secret')
# hash the string with RSA-SHA1
s = self.PKCS1_v1_5.new(consumer_secret)
# PyCrypto SHA.new requires an encoded byte string
h = self.SHA.new(signature_base_string)
hashed = s.sign(h)
# return the signature
return base64.b64encode(hashed).decode() | def sign(self,
consumer_secret,
access_token_secret,
method,
url,
oauth_params,
req_kwargs) | Sign request parameters.
:param consumer_secret: RSA private key.
:type consumer_secret: str or RSA._RSAobj
:param access_token_secret: Unused.
:type access_token_secret: str
:param method: The method of this particular request.
:type method: str
:param url: The URL of this particular request.
:type url: str
:param oauth_params: OAuth parameters.
:type oauth_params: dict
:param req_kwargs: Keyworded args that will be sent to the request
method.
:type req_kwargs: dict | 3.026238 | 2.321617 | 1.303504 |
'''Sign request using PLAINTEXT method.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret (optional).
:type access_token_secret: str
:param method: Unused
:type method: str
:param url: Unused
:type url: str
:param oauth_params: Unused
:type oauth_params: dict
:param req_kwargs: Unused
:type req_kwargs: dict
'''
key = self._escape(consumer_secret) + b'&'
if access_token_secret:
key += self._escape(access_token_secret)
return key.decode() | def sign(self, consumer_secret, access_token_secret, method, url,
oauth_params, req_kwargs) | Sign request using PLAINTEXT method.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret (optional).
:type access_token_secret: str
:param method: Unused
:type method: str
:param url: Unused
:type url: str
:param oauth_params: Unused
:type oauth_params: dict
:param req_kwargs: Unused
:type req_kwargs: dict | 2.24709 | 1.725574 | 1.302227 |
'''
If provided a `token` parameter, tries to retrieve a stored
`rauth.OAuth1Session` instance. Otherwise generates a new session
instance with the :class:`rauth.OAuth1Service.consumer_key` and
:class:`rauth.OAuth1Service.consumer_secret` stored on the
`rauth.OAuth1Service` instance.
:param token: A tuple of strings with which to memoize the session
object instance.
:type token: tuple
'''
if token is not None:
access_token, access_token_secret = token
session = self.session_obj(self.consumer_key,
self.consumer_secret,
access_token,
access_token_secret,
signature or self.signature_obj,
service=self)
else: # pragma: no cover
signature = signature or self.signature_obj
session = self.session_obj(self.consumer_key,
self.consumer_secret,
signature=signature,
service=self)
return session | def get_session(self, token=None, signature=None) | If provided a `token` parameter, tries to retrieve a stored
`rauth.OAuth1Session` instance. Otherwise generates a new session
instance with the :class:`rauth.OAuth1Service.consumer_key` and
:class:`rauth.OAuth1Service.consumer_secret` stored on the
`rauth.OAuth1Service` instance.
:param token: A tuple of strings with which to memoize the session
object instance.
:type token: tuple | 3.544944 | 1.708161 | 2.075299 |
'''
Returns a Requests' response over the
:attr:`rauth.OAuth1Service.request_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
# ensure we've set the request_token_url
if self.request_token_url is None:
raise TypeError('request_token_url must not be None')
session = self.get_session()
self.request_token_response = session.request(method,
self.request_token_url,
**kwargs)
return self.request_token_response | def get_raw_request_token(self, method='GET', **kwargs) | Returns a Requests' response over the
:attr:`rauth.OAuth1Service.request_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 4.616173 | 1.837699 | 2.511931 |
'''
Return a request token pair.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key_token: The key the access token will be decoded by, defaults
to 'oauth_token'.
:type string:
:param key_token_secret: The key the access token will be decoded by,
defaults to 'oauth_token_secret'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
r = self.get_raw_request_token(method=method, **kwargs)
request_token, request_token_secret = \
process_token_request(r, decoder, key_token, key_token_secret)
return request_token, request_token_secret | def get_request_token(self,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
**kwargs) | Return a request token pair.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key_token: The key the access token will be decoded by, defaults
to 'oauth_token'.
:type string:
:param key_token_secret: The key the access token will be decoded by,
defaults to 'oauth_token_secret'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 2.871777 | 1.434468 | 2.00198 |
'''
Returns a formatted authorize URL.
:param request_token: The request token as returned by
:class:`get_request_token`.
:type request_token: str
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*params: dict
'''
params.update({'oauth_token': request_token})
return self.authorize_url + '?' + urlencode(params) | def get_authorize_url(self, request_token, **params) | Returns a formatted authorize URL.
:param request_token: The request token as returned by
:class:`get_request_token`.
:type request_token: str
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*params: dict | 3.374844 | 1.711362 | 1.972023 |
'''
Returns a Requests' response over the
:attr:`rauth.OAuth1Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: str
:param method: A string representation of the HTTP method to be
used, defaults to `GET`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
# ensure we've set the access_token_url
if self.access_token_url is None:
raise TypeError('access_token_url must not be None')
session = self.get_session((request_token, request_token_secret))
self.access_token_response = session.request(method,
self.access_token_url,
**kwargs)
return self.access_token_response | def get_raw_access_token(self,
request_token,
request_token_secret,
method='GET',
**kwargs) | Returns a Requests' response over the
:attr:`rauth.OAuth1Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: str
:param method: A string representation of the HTTP method to be
used, defaults to `GET`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 3.210386 | 1.590304 | 2.018725 |
'''
Returns an access token pair.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: str
:param method: A string representation of the HTTP method to be
used, defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key_token: The key the access token will be decoded by, defaults
to 'oauth_token'.
:type string:
:param key_token_secret: The key the access token will be decoded by,
defaults to 'oauth_token_secret'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
r = self.get_raw_access_token(request_token,
request_token_secret,
method=method,
**kwargs)
access_token, access_token_secret = \
process_token_request(r, decoder, key_token, key_token_secret)
return access_token, access_token_secret | def get_access_token(self,
request_token,
request_token_secret,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
**kwargs) | Returns an access token pair.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: str
:param method: A string representation of the HTTP method to be
used, defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key_token: The key the access token will be decoded by, defaults
to 'oauth_token'.
:type string:
:param key_token_secret: The key the access token will be decoded by,
defaults to 'oauth_token_secret'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 2.328166 | 1.344435 | 1.731707 |
'''
Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: str
:param method: A string representation of the HTTP method to be
used, defaults to `GET`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
token = self.get_access_token(request_token,
request_token_secret,
method=method,
**kwargs)
session = self.get_session(token)
if self.request_token_response:
session.request_token_response = self.request_token_response
if self.access_token_response:
session.access_token_response = self.access_token_response
return session | def get_auth_session(self,
request_token,
request_token_secret,
method='GET',
**kwargs) | Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: str
:param method: A string representation of the HTTP method to be
used, defaults to `GET`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 2.475256 | 1.402964 | 1.764305 |
'''
If provided, the `token` parameter is used to initialize an
authenticated session, otherwise an unauthenticated session object is
generated. Returns an instance of :attr:`session_obj`..
:param token: A token with which to initilize the session.
:type token: str
'''
if token is not None:
session = self.session_obj(self.client_id,
self.client_secret,
token,
service=self)
else: # pragma: no cover
session = self.session_obj(self.client_id,
self.client_secret,
service=self)
return session | def get_session(self, token=None) | If provided, the `token` parameter is used to initialize an
authenticated session, otherwise an unauthenticated session object is
generated. Returns an instance of :attr:`session_obj`..
:param token: A token with which to initilize the session.
:type token: str | 3.706223 | 1.788521 | 2.072228 |
'''
Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
URL querystring.
:type \*\*params: dict
'''
params.update({'client_id': self.client_id})
return self.authorize_url + '?' + urlencode(params) | def get_authorize_url(self, **params) | Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
URL querystring.
:type \*\*params: dict | 4.150437 | 2.197922 | 1.888346 |
'''
Returns a Requests' response over the
:attr:`OAuth2Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
key = 'params'
if method in ENTITY_METHODS:
key = 'data'
kwargs.setdefault(key, {})
kwargs[key].update({'client_id': self.client_id,
'client_secret': self.client_secret})
session = self.get_session()
self.access_token_response = session.request(method,
self.access_token_url,
**kwargs)
return self.access_token_response | def get_raw_access_token(self, method='POST', **kwargs) | Returns a Requests' response over the
:attr:`OAuth2Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 3.989425 | 1.845562 | 2.161632 |
'''
Returns an access token.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key: The key the access token will be decoded by, defaults to
'access_token'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
r = self.get_raw_access_token(method, **kwargs)
access_token, = process_token_request(r, decoder, key)
return access_token | def get_access_token(self,
method='POST',
decoder=parse_utf8_qsl,
key='access_token',
**kwargs) | Returns an access token.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key: The key the access token will be decoded by, defaults to
'access_token'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 4.037211 | 1.760128 | 2.293703 |
'''
Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
session = self.get_session(self.get_access_token(method, **kwargs))
if self.access_token_response:
session.access_token_response = self.access_token_response
return session | def get_auth_session(self, method='POST', **kwargs) | Gets an access token, intializes a new authenticated session with the
access token. Returns an instance of :attr:`session_obj`.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict | 4.605535 | 1.844827 | 2.496459 |
'''
The token parameter should be `oFlyUserid`. This is used to initialize
an authenticated session instance. Returns an instance of
:attr:`session_obj`.
:param token: A token with which to initialize the session with, e.g.
:attr:`OflyService.user_id`.
:type token: str
'''
return self.session_obj(self.app_id,
self.app_secret,
token,
service=self) | def get_session(self, token) | The token parameter should be `oFlyUserid`. This is used to initialize
an authenticated session instance. Returns an instance of
:attr:`session_obj`.
:param token: A token with which to initialize the session with, e.g.
:attr:`OflyService.user_id`.
:type token: str | 9.216191 | 1.859965 | 4.955035 |
'''
Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*params: dict
'''
params = self.session_obj.sign(self.authorize_url,
self.app_id,
self.app_secret,
**params)
return self.authorize_url + '?' + params | def get_authorize_url(self, **params) | Returns a formatted authorize URL.
:param \*\*params: Additional keyworded arguments to be added to the
request querystring.
:type \*\*params: dict | 4.931492 | 2.809498 | 1.755293 |
self._channel.queue_declare(
queue=queue_name,
auto_delete=True,
durable=True,
)
self._channel.exchange_declare(
exchange=exchange_name,
exchange_type='topic',
auto_delete=True,
)
self._channel.queue_bind(
exchange=exchange_name,
queue=queue_name,
routing_key=routing_key
) | def bind_topic_exchange(self, exchange_name, routing_key, queue_name) | 绑定主题交换机和队列
:param exchange_name: 需要绑定的交换机名
:param routing_key:
:param queue_name: 需要绑定的交换机队列名
:return: | 1.616771 | 1.705039 | 0.948231 |
result = self._channel.queue_declare(
queue=queue_name,
passive=passive,
durable=durable,
exclusive=exclusive,
auto_delete=auto_delete,
arguments=arguments
)
return result.method.queue | def declare_queue(self, queue_name='', passive=False, durable=False,
exclusive=False, auto_delete=False, arguments=None) | 声明一个队列
:param queue_name: 队列名
:param passive:
:param durable:
:param exclusive:
:param auto_delete:
:param arguments:
:return: pika 框架生成的随机回调队列名 | 1.699114 | 1.866514 | 0.910314 |
self.bind_topic_exchange(exchange_name, routing_key, queue_name)
self.basic_consuming(
queue_name=queue_name,
callback=callback
) | def declare_consuming(self, exchange_name, routing_key, queue_name, callback) | 声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列
:param exchange_name:
:param routing_key:
:param queue_name:
:param callback:
:return: | 3.354526 | 3.305346 | 1.014879 |
self._channel.exchange_declare(exchange=exchange_name,
exchange_type=type)
self._channel.queue_bind(queue=queue,
exchange=exchange_name,
routing_key=routing_key) | def exchange_bind_to_queue(self, type, exchange_name, routing_key, queue) | Declare exchange and bind queue to exchange
:param type: The type of exchange
:param exchange_name: The name of exchange
:param routing_key: The key of exchange bind to queue
:param queue: queue name | 1.930129 | 1.903876 | 1.013789 |
self.data[key]['isAccept'] = True # 设置为已经接受到服务端返回的消息
self.data[key]['result'] = str(result)
self._channel.queue_delete(self.data[key]['reply_queue_name']) | def accept(self, key, result) | 同步接受确认消息
:param key: correlation_id
:param result 服务端返回的消息 | 6.446749 | 5.289946 | 1.21868 |
logger.info("on response => {}".format(body))
corr_id = props.correlation_id # 从props得到服务端返回的客户端传入的corr_id值
self.accept(corr_id, body) | def on_response(self, ch, method, props, body) | All RPC response will call this method, so change the isAccept to True in this method
所有的RPC请求回调都会调用该方法,在该方法内修改对应corr_id已经接受消息的isAccept值和返回结果 | 9.763563 | 7.153625 | 1.364841 |
result = self.declare_queue(
queue_name=queue_name,passive=passive,
durable=durable,exclusive=exclusive,
auto_delete=auto_delete,arguments=arguments
)
self.declare_basic_consuming(
queue_name=queue_name,
callback=callback
)
return result | def declare_default_consuming(self, queue_name, callback, passive=False,
durable=False,exclusive=False, auto_delete=False,
arguments=None) | 声明一个默认的交换机的队列,并且监听这个队列
:param queue_name:
:param callback:
:return: | 2.209286 | 2.39344 | 0.923059 |
self.bind_topic_exchange(exchange_name, routing_key, queue_name)
self.declare_basic_consuming(
queue_name=queue_name,
callback=callback
) | def declare_consuming(self, exchange_name, routing_key, queue_name, callback) | 声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列
:param exchange_name:
:param routing_key:
:param queue_name:
:param callback:
:return: | 3.469295 | 3.72574 | 0.93117 |
callback_queue = self.declare_queue(exclusive=True,
auto_delete=True) # 得到随机回调队列名
self._channel.basic_consume(self.on_response, # 客户端消费回调队列
no_ack=True,
queue=callback_queue)
corr_id = str(uuid.uuid4()) # 生成客户端请求id
self.data[corr_id] = {
'isAccept': False,
'result': None,
'callbackQueue': callback_queue
}
self._channel.basic_publish( # 发送数据给服务端
exchange=exchange,
routing_key=key,
body=body,
properties=pika.BasicProperties(
reply_to=callback_queue,
correlation_id=corr_id,
)
)
while not self.data[corr_id]['isAccept']: # 判断是否接收到服务端返回的消息
self._connection.process_data_events()
time.sleep(0.3)
continue
logger.info("Got the RPC server response => {}".format(self.data[corr_id]['result']))
return self.data[corr_id]['result'] | def send_sync(self, body, exchange, key) | 发送并同步接受回复消息
:return: | 3.046007 | 3.017227 | 1.009538 |
username = user.get('username')
password = user.get('password')
the_username = os.environ.get(
'SIMPLELOGIN_USERNAME',
current_app.config.get('SIMPLELOGIN_USERNAME', 'admin')
)
the_password = os.environ.get(
'SIMPLELOGIN_PASSWORD',
current_app.config.get('SIMPLELOGIN_PASSWORD', 'secret')
)
if username == the_username and password == the_password:
return True
return False | def default_login_checker(user) | user must be a dictionary here default is
checking username/password
if login is ok returns True else False
:param user: dict {'username':'', 'password': ''} | 2.180242 | 2.115706 | 1.030503 |
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return 'simple_logged_in' in session and get_username() in username
return 'simple_logged_in' in session | def is_logged_in(username=None) | Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list | 3.813661 | 4.143824 | 0.920324 |
if function and not callable(function):
raise ValueError(
'Decorator receives only named arguments, '
'try login_required(username="foo")'
)
def check(validators):
if validators is None:
return
if not isinstance(validators, (list, tuple)):
validators = [validators]
for validator in validators:
error = validator(get_username())
if error is not None:
return SimpleLogin.get_message('auth_error', error), 403
def dispatch(fun, *args, **kwargs):
if basic and request.is_json:
return dispatch_basic_auth(fun, *args, **kwargs)
if is_logged_in(username=username):
return check(must) or fun(*args, **kwargs)
elif is_logged_in():
return SimpleLogin.get_message('access_denied'), 403
else:
flash(SimpleLogin.get_message('login_required'), 'warning')
return redirect(url_for('simplelogin.login', next=request.path))
def dispatch_basic_auth(fun, *args, **kwargs):
simplelogin = current_app.extensions['simplelogin']
auth_response = simplelogin.basic_auth()
if auth_response is True:
return check(must) or fun(*args, **kwargs)
else:
return auth_response
if function:
@wraps(function)
def simple_decorator(*args, **kwargs):
return dispatch(function, *args, **kwargs)
return simple_decorator
def decorator(f):
@wraps(f)
def wrap(*args, **kwargs):
return dispatch(f, *args, **kwargs)
return wrap
return decorator | def login_required(function=None, username=None, basic=False, must=None) | Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function]) | 2.797428 | 2.792772 | 1.001667 |
msg = current_app.extensions['simplelogin'].messages.get(message)
if msg and (args or kwargs):
return msg.format(*args, **kwargs)
return msg | def get_message(message, *args, **kwargs) | Helper to get internal messages outside this instance | 4.761154 | 4.260412 | 1.117534 |
auth = request.authorization
if auth and self._login_checker({'username': auth.username,
'password': auth.password}):
session['simple_logged_in'] = True
session['simple_basic_auth'] = True
session['simple_username'] = auth.username
return response or True
else:
headers = {'WWW-Authenticate': 'Basic realm="Login Required"'}
return 'Invalid credentials', 401, headers | def basic_auth(self, response=None) | Support basic_auth via /login or login_required(basic=True) | 3.450826 | 3.224799 | 1.07009 |
user_data = my_users.get(user['username'])
if not user_data:
return False # <--- invalid credentials
elif user_data.get('password') == user['password']:
return True # <--- user is logged in!
return False | def check_my_users(user) | Check if user exists and its credentials.
Take a look at encrypt_app.py and encrypt_cli.py
to see how to encrypt passwords | 4.442823 | 4.399422 | 1.009865 |
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
# Hash the user password
data['password'] = generate_password_hash(
data.pop('password'),
method='pbkdf2:sha256'
)
# Here you insert the `data` in your users database
# for this simple example we are recording in a json file
db_users = json.load(open('users.json'))
# add the new created user to json
db_users[data['username']] = data
# commit changes to database
json.dump(db_users, open('users.json', 'w'))
return data | def create_user(**data) | Creates user with encrypted password | 3.734946 | 3.60616 | 1.035713 |
@wraps(f)
def decorator(*args, **kwargs):
app = create_app()
configure_extensions(app)
configure_views(app)
return f(app=app, *args, **kwargs)
return decorator | def with_app(f) | Calls function passing app as first argument | 2.624754 | 2.81672 | 0.931848 |
with app.app_context():
create_user(username=username, password=password)
click.echo('user created!') | def adduser(app, username, password) | Add new user with admin access | 4.199896 | 4.216334 | 0.996101 |
debug = debug or app.config.get('DEBUG', False)
reloader = reloader or app.config.get('RELOADER', False)
host = host or app.config.get('HOST', '127.0.0.1')
port = port or app.config.get('PORT', 5000)
app.run(
use_reloader=reloader,
debug=debug,
host=host,
port=port
) | def runserver(app=None, reloader=None, debug=None, host=None, port=None) | Run the Flask development server i.e. app.run() | 1.483035 | 1.486651 | 0.997568 |
if self._i2c_expander == 'PCF8574':
self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight))
c.usleep(1)
self.bus.write_byte(self._address, value | PCF8574_E | self._backlight)
c.usleep(1)
self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight))
c.usleep(100)
elif self._i2c_expander in ['MCP23008', 'MCP23017']:
self._mcp_data &= ~MCP230XX_DATAMASK
self._mcp_data |= value << MCP230XX_DATASHIFT
self._mcp_data &= ~MCP230XX_E
self.bus.write_byte_data(self._address, self._mcp_gpio, self._mcp_data)
c.usleep(1)
self._mcp_data |= MCP230XX_E
self.bus.write_byte_data(self._address, self._mcp_gpio, self._mcp_data)
c.usleep(1)
self._mcp_data &= ~MCP230XX_E
self.bus.write_byte_data(self._address, self._mcp_gpio, self._mcp_data)
c.usleep(100) | def _pulse_data(self, value) | Pulse the `enable` flag to process value. | 1.929672 | 1.895497 | 1.01803 |
# Wait, if compatibility mode is enabled
if self.compat_mode:
self._wait()
# Choose instruction or data mode
GPIO.output(self.pins.rs, mode)
# If the RW pin is used, set it to low in order to write.
if self.pins.rw is not None:
GPIO.output(self.pins.rw, 0)
# Write data out in chunks of 4 or 8 bit
if self.data_bus_mode == c.LCD_8BITMODE:
self._write8bits(value)
else:
self._write4bits(value >> 4)
self._write4bits(value)
# Record the time for the tail-end of the last send event
if self.compat_mode:
self.last_send_event = now() | def _send(self, value, mode) | Send the specified value to the display with automatic 4bit / 8bit
selection. The rs_mode is either ``RS_DATA`` or ``RS_INSTRUCTION``. | 5.787616 | 5.126752 | 1.128905 |
for i in range(4):
bit = (value >> i) & 0x01
GPIO.output(self.pins[i + 7], bit)
self._pulse_enable() | def _write4bits(self, value) | Write 4 bits of data into the data bus. | 3.992152 | 3.91735 | 1.019095 |
GPIO.output(self.pins.e, 0)
c.usleep(1)
GPIO.output(self.pins.e, 1)
c.usleep(1)
GPIO.output(self.pins.e, 0)
c.usleep(100) | def _pulse_enable(self) | Pulse the `enable` flag to process data. | 2.762142 | 2.76135 | 1.000287 |
encoded = self.codec.encode(value) # type: List[int]
ignored = False
for [char, lookahead] in c.sliding_window(encoded, lookahead=1):
# If the previous character has been ignored, skip this one too.
if ignored is True:
ignored = False
continue
# Write regular chars
if char not in [codecs.CR, codecs.LF]:
self.write(char)
continue
# We're now left with only CR and LF characters. If an auto
# linebreak happened recently, and the lookahead matches too,
# ignore this write.
if self.recent_auto_linebreak is True:
crlf = (char == codecs.CR and lookahead == codecs.LF)
lfcr = (char == codecs.LF and lookahead == codecs.CR)
if crlf or lfcr:
ignored = True
continue
# Handle newlines and carriage returns
row, col = self.cursor_pos
if char == codecs.LF:
if row < self.lcd.rows - 1:
self.cursor_pos = (row + 1, col)
else:
self.cursor_pos = (0, col)
elif char == codecs.CR:
if self.text_align_mode == 'left':
self.cursor_pos = (row, 0)
else:
self.cursor_pos = (row, self.lcd.cols - 1) | def write_string(self, value) | Write the specified unicode string to the display.
To control multiline behavior, use newline (``\\n``) and carriage
return (``\\r``) characters.
Lines that are too long automatically continue on next line, as long as
``auto_linebreaks`` has not been disabled.
Make sure that you're only passing unicode objects to this function.
The unicode string is then converted to the correct LCD encoding by
using the charmap specified at instantiation time.
If you're dealing with bytestrings (the default string type in Python
2), convert it to a unicode object using the ``.decode(encoding)``
method and the appropriate encoding. Example for UTF-8 encoded strings:
.. code::
>>> bstring = 'Temperature: 30°C'
>>> bstring
'Temperature: 30\xc2\xb0C'
>>> bstring.decode('utf-8')
u'Temperature: 30\xb0C' | 3.936735 | 4.105632 | 0.958862 |
self.command(c.LCD_CLEARDISPLAY)
self._cursor_pos = (0, 0)
self._content = [[0x20] * self.lcd.cols for _ in range(self.lcd.rows)]
c.msleep(2) | def clear(self) | Overwrite display with blank characters and reset cursor position. | 5.855906 | 5.520256 | 1.060803 |
self.command(c.LCD_RETURNHOME)
self._cursor_pos = (0, 0)
c.msleep(2) | def home(self) | Set cursor to initial position and reset any shifting. | 11.788068 | 8.210873 | 1.435666 |
if amount == 0:
return
direction = c.LCD_MOVERIGHT if amount > 0 else c.LCD_MOVELEFT
for i in range(abs(amount)):
self.command(c.LCD_CURSORSHIFT | c.LCD_DISPLAYMOVE | direction)
c.usleep(50) | def shift_display(self, amount) | Shift the display. Use negative amounts to shift left and positive
amounts to shift right. | 3.444001 | 3.266842 | 1.05423 |
assert 0 <= location <= 7, 'Only locations 0-7 are valid.'
assert len(bitmap) == 8, 'Bitmap should have exactly 8 rows.'
# Store previous position
pos = self.cursor_pos
# Write character to CGRAM
self.command(c.LCD_SETCGRAMADDR | location << 3)
for row in bitmap:
self._send_data(row)
# Restore cursor pos
self.cursor_pos = pos | def create_char(self, location, bitmap) | Create a new character.
The HD44780 supports up to 8 custom characters (location 0-7).
:param location: The place in memory where the character is stored.
Values need to be integers between 0 and 7.
:type location: int
:param bitmap: The bitmap containing the character. This should be a
tuple of 8 numbers, each representing a 5 pixel row.
:type bitmap: tuple of int
:raises AssertionError: Raised when an invalid location is passed in or
when bitmap has an incorrect size.
Example:
.. sourcecode:: python
>>> smiley = (
... 0b00000,
... 0b01010,
... 0b01010,
... 0b00000,
... 0b10001,
... 0b10001,
... 0b01110,
... 0b00000,
... )
>>> lcd.create_char(0, smiley) | 5.001634 | 4.790182 | 1.044143 |
if self._content[row][col] != value:
self._send_data(value)
self._content[row][col] = value # Update content cache
unchanged = False
else:
unchanged = True
except IndexError as e:
# Position out of range
if self.auto_linebreaks is True:
raise e
self._send_data(value)
unchanged = False
# Update cursor position.
if self.text_align_mode == 'left':
if self.auto_linebreaks is False or col < self.lcd.cols - 1:
# No newline, update internal pointer
newpos = (row, col + 1)
if unchanged:
self.cursor_pos = newpos
else:
self._cursor_pos = newpos
self.recent_auto_linebreak = False
else:
# Newline, reset pointer
if row < self.lcd.rows - 1:
self.cursor_pos = (row + 1, 0)
else:
self.cursor_pos = (0, 0)
self.recent_auto_linebreak = True
else:
if self.auto_linebreaks is False or col > 0:
# No newline, update internal pointer
newpos = (row, col - 1)
if unchanged:
self.cursor_pos = newpos
else:
self._cursor_pos = newpos
self.recent_auto_linebreak = False
else:
# Newline, reset pointer
if row < self.lcd.rows - 1:
self.cursor_pos = (row + 1, self.lcd.cols - 1)
else:
self.cursor_pos = (0, self.lcd.cols - 1)
self.recent_auto_linebreak = True | def write(self, value): # type: (int) -> None
# Get current position
row, col = self._cursor_pos
# Write byte if changed
try | Write a raw byte to the LCD. | 2.166433 | 2.08942 | 1.036859 |
warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning)
lcd.cursor_pos = (row, col)
yield | def cursor(lcd, row, col) | Context manager to control cursor position. DEPRECATED. | 6.146165 | 4.156987 | 1.478514 |
it = itertools.chain(iter(seq), ' ' * lookahead) # Padded iterator
window_size = lookahead + 1
result = tuple(itertools.islice(it, window_size))
if len(result) == window_size:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result | def sliding_window(seq, lookahead) | Create a sliding window with the specified number of lookahead characters. | 2.810539 | 2.728564 | 1.030043 |
# Assemble the parameters sent to the pigpio script
params = [mode]
params.extend([(value >> i) & 0x01 for i in range(8)])
# Switch off pigpio's exceptions, so that we get the return codes
pigpio.exceptions = False
while True:
ret = self.pi.run_script(self._writescript, params)
if ret >= 0:
break
elif ret != pigpio.PI_SCRIPT_NOT_READY:
raise pigpio.error(pigpio.error_text(ret))
# If pigpio script is not ready, sleep and try again
c.usleep(1)
# Switch on pigpio's exceptions
pigpio.exceptions = True | def _send(self, value, mode) | Send the specified value to the display with automatic 4bit / 8bit
selection. The rs_mode is either ``RS_DATA`` or ``RS_INSTRUCTION``. | 5.408223 | 5.285299 | 1.023258 |
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=float,
default=10.0,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("--run-from-stdin",
action="store_true",
default=False,
help="Read cmds from stdin, run them and exit")
parser.add_argument("--sync-connect",
action="store_true",
default=False,
help="Connect synchronously.")
parser.add_argument("--readonly",
action="store_true",
default=False,
help="Enable readonly.")
parser.add_argument("--tunnel",
type=str,
help="Create a ssh tunnel via this host",
default=None)
parser.add_argument("--version",
action="store_true",
default=False,
help="Display version and exit.")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
params = parser.parse_args()
return CLIParams(
params.connect_timeout,
params.run_once,
params.run_from_stdin,
params.sync_connect,
params.hosts,
params.readonly,
params.tunnel,
params.version
) | def get_params() | get the cmdline params | 2.431401 | 2.380575 | 1.02135 |
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdout) | def set_unbuffered_mode() | make output unbuffered | 1.470603 | 1.381965 | 1.064139 |
try:
scheme, rest = acl.split(":", 1)
credential = ":".join(rest.split(":")[0:-1])
cdrwa = rest.split(":")[-1]
except ValueError:
raise cls.BadACL("Bad ACL: %s. Format is scheme:id:perms" % (acl))
if scheme not in cls.valid_schemes:
raise cls.BadACL("Invalid scheme: %s" % (acl))
create = True if "c" in cdrwa else False
read = True if "r" in cdrwa else False
write = True if "w" in cdrwa else False
delete = True if "d" in cdrwa else False
admin = True if "a" in cdrwa else False
if scheme == "username_password":
try:
username, password = credential.split(":", 1)
except ValueError:
raise cls.BadACL("Bad ACL: %s. Format is scheme:id:perms" % (acl))
return make_digest_acl(username,
password,
read,
write,
create,
delete,
admin)
else:
return make_acl(scheme,
credential,
read,
write,
create,
delete,
admin) | def extract_acl(cls, acl) | parse an individual ACL (i.e.: world:anyone:cdrwa) | 2.366831 | 2.197365 | 1.077122 |
return {
"perms": acl.perms,
"id": {
"scheme": acl.id.scheme,
"id": acl.id.id
}
} | def to_dict(cls, acl) | transform an ACL to a dict | 3.880218 | 3.368897 | 1.151777 |
perms = acl_dict.get("perms", Permissions.ALL)
id_dict = acl_dict.get("id", {})
id_scheme = id_dict.get("scheme", "world")
id_id = id_dict.get("id", "anyone")
return ACL(perms, Id(id_scheme, id_id)) | def from_dict(cls, acl_dict) | ACL from dict | 3.522723 | 3.298056 | 1.068121 |
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if not self.connected:
self.show_output("Not connected.")
else:
try:
return func(*args, **kwargs)
except APIError:
self.show_output("ZooKeeper internal error.")
except AuthFailedError:
self.show_output("Authentication failed.")
except NoAuthError:
self.show_output("Not authenticated.")
except BadVersionError:
self.show_output("Bad version.")
except ConnectionLoss:
self.show_output("Connection loss.")
except NotReadOnlyCallError:
self.show_output("Not a read-only operation.")
except BadArgumentsError:
self.show_output("Bad arguments.")
except SessionExpiredError:
self.show_output("Session expired.")
except UnimplementedError as ex:
self.show_output("Not implemented by the server: %s." % str(ex))
except ZookeeperError as ex:
self.show_output("Unknown ZooKeeper error: %s" % str(ex))
return wrapper | def connected(func) | check connected, fails otherwise | 2.368949 | 2.330699 | 1.016411 |
@wraps(func)
def wrapper(*args):
self = args[0]
params = args[1]
if not self.in_transaction:
for name in path_params:
value = getattr(params, name)
paths = value if type(value) == list else [value]
resolved = []
for path in paths:
path = self.resolve_path(path)
if not self.client.exists(path):
self.show_output("Path %s doesn't exist", path)
return False
resolved.append(path)
if type(value) == list:
setattr(params, name, resolved)
else:
setattr(params, name, resolved[0])
return func(self, params)
return wrapper | def check_path_exists_foreach(path_params, func) | check that paths exist (unless we are in a transaction) | 2.67218 | 2.356742 | 1.133845 |
@wraps(func)
def wrapper(*args):
self = args[0]
params = args[1]
orig_path = params.path
sequence = getattr(params, 'sequence', False)
params.path = self.resolve_path(params.path)
if self.in_transaction or sequence or not self.client.exists(params.path):
if sequence and orig_path.endswith("/") and params.path != "/":
params.path += "/"
return func(self, params)
self.show_output("Path %s already exists", params.path)
return wrapper | def check_path_absent(func) | check path doesn't exist (unless we are in a txn or it's sequential)
note: when creating sequential znodes, a trailing slash means no prefix, i.e.:
create(/some/path/, sequence=True) -> /some/path/0000001
for all other cases, it's dropped. | 3.666348 | 3.314633 | 1.10611 |
if full_cmd.endswith(" "):
cmd_param, path = " ", " "
else:
pieces = shlex.split(full_cmd)
if len(pieces) > 1:
cmd_param = pieces[-1]
else:
cmd_param = cmd_param_text
path = cmd_param.rstrip("/") if cmd_param != "/" else "/"
if re.match(r"^\s*$", path):
return self._zk.get_children(self.curdir)
rpath = self.resolve_path(path)
if self._zk.exists(rpath):
opts = [os.path.join(path, znode) for znode in self._zk.get_children(rpath)]
else:
parent, child = os.path.dirname(rpath), os.path.basename(rpath)
relpath = os.path.dirname(path)
to_rel = lambda n: os.path.join(relpath, n) if relpath != "" else n
opts = [to_rel(n) for n in self._zk.get_children(parent) if n.startswith(child)]
offs = len(cmd_param) - len(cmd_param_text)
return [opt[offs:] for opt in opts] | def _complete_path(self, cmd_param_text, full_cmd, *_) | completes paths | 2.980738 | 2.912539 | 1.023415 |
self._zk.add_auth(params.scheme, params.credential) | def do_add_auth(self, params) | \x1b[1mNAME\x1b[0m
add_auth - Authenticates the session
\x1b[1mSYNOPSIS\x1b[0m
add_auth <scheme> <credential>
\x1b[1mEXAMPLES\x1b[0m
> add_auth digest super:s3cr3t | 11.091653 | 11.168815 | 0.993091 |
try:
acls = ACLReader.extract(shlex.split(params.acls))
except ACLReader.BadACL as ex:
self.show_output("Failed to set ACLs: %s.", ex)
return
def set_acls(path):
try:
self._zk.set_acls(path, acls)
except (NoNodeError, BadVersionError, InvalidACLError, ZookeeperError) as ex:
self.show_output("Failed to set ACLs: %s. Error: %s", str(acls), str(ex))
if params.recursive:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
set_acls(cpath)
set_acls(params.path) | def do_set_acls(self, params) | \x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
set_acls <path> <acls> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively set the acls on the children
\x1b[1mEXAMPLES\x1b[0m
> set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLkq04bvo=:cdrwa'
> set_acls /some/path 'world:anyone:r username_password:user:p@ass0rd:cdrwa'
> set_acls /path 'world:anyone:r' true | 3.386688 | 3.641564 | 0.930009 |
possible_acl = [
"digest:",
"username_password:",
"world:anyone:c",
"world:anyone:cd",
"world:anyone:cdr",
"world:anyone:cdrw",
"world:anyone:cdrwa",
]
complete_acl = partial(complete_values, possible_acl)
completers = [self._complete_path, complete_acl, complete_labeled_boolean("recursive")]
return complete(completers, cmd_param_text, full_cmd, *rest) | def complete_set_acls(self, cmd_param_text, full_cmd, *rest) | FIXME: complete inside a quoted param is broken | 5.032146 | 4.670736 | 1.077378 |
def replace(plist, oldv, newv):
try:
plist.remove(oldv)
plist.insert(0, newv)
except ValueError:
pass
for path, acls in self._zk.get_acls_recursive(params.path, params.depth, params.ephemerals):
replace(acls, READ_ACL_UNSAFE[0], "WORLD_READ")
replace(acls, OPEN_ACL_UNSAFE[0], "WORLD_ALL")
self.show_output("%s: %s", path, acls) | def do_get_acls(self, params) | \x1b[1mNAME\x1b[0m
get_acls - Gets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
get_acls <path> [depth] [ephemerals]
\x1b[1mOPTIONS\x1b[0m
* depth: -1 is no recursion, 0 is infinite recursion, N > 0 is up to N levels (default: 0)
* ephemerals: include ephemerals (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get_acls /zookeeper
[ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
> get_acls /zookeeper -1
/zookeeper: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/config: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))]
/zookeeper/quota: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))] | 4.774691 | 3.92399 | 1.216795 |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
znodes = self._zk.get_children(params.path, **kwargs)
self.show_output(params.sep.join(sorted(znodes))) | def do_ls(self, params) | \x1b[1mNAME\x1b[0m
ls - Lists the znodes for the given <path>
\x1b[1mSYNOPSIS\x1b[0m
ls <path> [watch] [sep]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (child) watch on the path (default: false)
* sep: separator to be used (default: '\\n')
\x1b[1mEXAMPLES\x1b[0m
> ls /
configs
zookeeper
Setting a watch:
> ls / true
configs
zookeeper
> create /foo 'bar'
WatchedEvent(type='CHILD', state='CONNECTED', path=u'/')
> ls / false ,
configs,zookeeper | 6.053167 | 4.692601 | 1.289939 |
wm = get_watch_manager(self._zk)
if params.command == "start":
debug = to_bool(params.debug)
children = to_int(params.sleep, -1)
wm.add(params.path, debug, children)
elif params.command == "stop":
wm.remove(params.path)
elif params.command == "stats":
repeat = to_int(params.debug, 1)
sleep = to_int(params.sleep, 1)
if repeat == 0:
while True:
wm.stats(params.path)
time.sleep(sleep)
else:
for _ in range(0, repeat):
wm.stats(params.path)
time.sleep(sleep)
else:
self.show_output("watch <start|stop|stats> <path> [verbose]") | def do_watch(self, params) | \x1b[1mNAME\x1b[0m
watch - Recursively watch for all changes under a path.
\x1b[1mSYNOPSIS\x1b[0m
watch <start|stop|stats> <path> [options]
\x1b[1mDESCRIPTION\x1b[0m
watch start <path> [debug] [depth]
with debug=true, print watches as they fire. depth is
the level for recursively setting watches:
* -1: recurse all the way
* 0: don't recurse, only watch the given path
* > 0: recurse up to <level> children
watch stats <path> [repeat] [sleep]
with repeat=0 this command will loop until interrupted. sleep sets
the pause duration in between each iteration.
watch stop <path>
\x1b[1mEXAMPLES\x1b[0m
> watch start /foo/bar
> watch stop /foo/bar
> watch stats /foo/bar | 3.139927 | 2.87053 | 1.093849 |
try:
self.copy(params, params.recursive, params.overwrite, params.max_items, False)
except AuthFailedError:
self.show_output("Authentication failed.") | def do_cp(self, params) | \x1b[1mNAME\x1b[0m
cp - Copy from/to local/remote or remote/remote paths
\x1b[1mSYNOPSIS\x1b[0m
cp <src> <dst> [recursive] [overwrite] [asynchronous] [verbose] [max_items]
\x1b[1mDESCRIPTION\x1b[0m
src and dst can be:
/some/path (in the connected server)
zk://[scheme:user:passwd@]host/<path>
json://!some!path!backup.json/some/path
file:///some/file
with a few restrictions. Given the semantic differences that znodes have with filesystem
directories recursive copying from znodes to an fs could lose data, but to a JSON file it
would work just fine.
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively copy src (default: false)
* overwrite: overwrite the dst path (default: false)
* asynchronous: do asynchronous copies (default: false)
* verbose: verbose output of every path (default: false)
* max_items: max number of paths to copy (0 is infinite) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> cp /some/znode /backup/copy-znode # local
> cp /some/znode zk://digest:bernie:[email protected]/backup true true
> cp /some/znode json://!home!user!backup.json/ true true
> cp file:///tmp/file /some/zone # fs to zk | 11.310551 | 8.997893 | 1.257022 |
question = "Are you sure you want to replace %s with %s?" % (params.dst, params.src)
if params.skip_prompt or self.prompt_yes_no(question):
self.copy(params, True, True, 0, True) | def do_mirror(self, params) | \x1b[1mNAME\x1b[0m
mirror - Mirrors from/to local/remote or remote/remote paths
\x1b[1mSYNOPSIS\x1b[0m
mirror <src> <dst> [async] [verbose] [skip_prompt]
\x1b[1mDESCRIPTION\x1b[0m
src and dst can be:
/some/path (in the connected server)
zk://[user:passwd@]host/<path>
json://!some!path!backup.json/some/path
with a few restrictions. Given the semantic differences that znodes have with filesystem
directories recursive copying from znodes to an fs could lose data, but to a JSON file it
would work just fine.
The dst subtree will be modified to look the same as the src subtree with the exception
of ephemeral nodes.
\x1b[1mOPTIONS\x1b[0m
* async: do asynchronous copies (default: false)
* verbose: verbose output of every path (default: false)
* skip_prompt: don't ask for confirmation (default: false)
\x1b[1mEXAMPLES\x1b[0m
> mirror /some/znode /backup/copy-znode # local
> mirror /some/path json://!home!user!backup.json/ true true | 5.237584 | 5.125145 | 1.021939 |
self.show_output(".")
for child, level in self._zk.tree(params.path, params.max_depth):
self.show_output(u"%s├── %s", u"│ " * level, child) | def do_tree(self, params) | \x1b[1mNAME\x1b[0m
tree - Print the tree under a given path
\x1b[1mSYNOPSIS\x1b[0m
tree [path] [max_depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> tree
.
├── zookeeper
│ ├── config
│ ├── quota
> tree 1
.
├── zookeeper
├── foo
├── bar | 8.255768 | 9.987736 | 0.826591 |
for child, level in self._zk.tree(params.path, params.depth, full_path=True):
self.show_output("%s: %d", child, self._zk.child_count(child)) | def do_child_count(self, params) | \x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1mEXAMPLES\x1b[0m
> child-count /
/zookeeper: 2
/foo: 0
/bar: 3 | 8.301545 | 8.07756 | 1.027729 |
self.show_output(pretty_bytes(self._zk.du(params.path))) | def do_du(self, params) | \x1b[1mNAME\x1b[0m
du - Total number of bytes under a path
\x1b[1mSYNOPSIS\x1b[0m
du [path]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
\x1b[1mEXAMPLES\x1b[0m
> du /
90 | 21.25708 | 31.2407 | 0.680429 |
for path in self._zk.find(params.path, params.match, 0):
self.show_output(path) | def do_find(self, params) | \x1b[1mNAME\x1b[0m
find - Find znodes whose path matches a given text
\x1b[1mSYNOPSIS\x1b[0m
find [path] [match]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* match: the string to match in the paths (default: '')
\x1b[1mEXAMPLES\x1b[0m
> find / foo
/foo2
/fooish/wayland
/fooish/xorg
/copy/foo | 10.583858 | 12.491617 | 0.847277 |
seen = set()
# we don't want to recurse once there's a child matching, hence exclude_recurse=
for path in self._zk.fast_tree(params.path, exclude_recurse=params.pattern):
parent, child = split(path)
if parent in seen:
continue
match = params.pattern in child
if params.inverse:
if not match:
self.show_output(parent)
seen.add(parent)
else:
if match:
self.show_output(parent)
seen.add(parent) | def do_child_matches(self, params) | \x1b[1mNAME\x1b[0m
child_matches - Prints paths that have at least 1 child that matches <pattern>
\x1b[1mSYNOPSIS\x1b[0m
child_matches <path> <pattern> [inverse]
\x1b[1mOPTIONS\x1b[0m
* inverse: display paths which don't match (default: false)
\x1b[1mEXAMPLES\x1b[0m
> child_matches /services/registrations member_
/services/registrations/foo
/services/registrations/bar
... | 5.882597 | 5.296146 | 1.110732 |
self.show_output("%s%s%s%s",
"Created".ljust(32),
"Last modified".ljust(32),
"Owner".ljust(23),
"Name")
results = sorted(self._zk.stat_map(params.path))
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
offs = 1 if params.path == "/" else len(params.path) + 1
for i in range(start, end):
path, stat = results[i]
self.show_output(
"%s%s%s%s",
time.ctime(stat.created).ljust(32),
time.ctime(stat.last_modified).ljust(32),
("0x%x" % stat.ephemeralOwner).ljust(23),
path[offs:]
) | def do_summary(self, params) | \x1b[1mNAME\x1b[0m
summary - Prints summarized details of a path's children
\x1b[1mSYNOPSIS\x1b[0m
summary [path] [top]
\x1b[1mDESCRIPTION\x1b[0m
The results are sorted by name.
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* top: number of results to be displayed (0 is all) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> summary /services/registrations
Created Last modified Owner Name
Thu Oct 11 09:14:39 2014 Thu Oct 11 09:14:39 2014 - bar
Thu Oct 16 18:54:39 2014 Thu Oct 16 18:54:39 2014 - foo
Thu Oct 12 10:04:01 2014 Thu Oct 12 10:04:01 2014 0x14911e869aa0dc1 member_0000001 | 3.121185 | 2.689975 | 1.160303 |
for path in self._zk.find(params.path, params.match, re.IGNORECASE):
self.show_output(path) | def do_ifind(self, params) | \x1b[1mNAME\x1b[0m
ifind - Find znodes whose path (insensitively) matches a given text
\x1b[1mSYNOPSIS\x1b[0m
ifind [path] [match]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* match: the string to match in the paths (default: '')
\x1b[1mEXAMPLES\x1b[0m
> ifind / fOO
/foo2
/FOOish/wayland
/fooish/xorg
/copy/Foo | 10.449045 | 10.657477 | 0.980443 |
self.grep(params.path, params.content, 0, params.show_matches) | def do_grep(self, params) | \x1b[1mNAME\x1b[0m
grep - Prints znodes with a value matching the given text
\x1b[1mSYNOPSIS\x1b[0m
grep [path] <content> [show_matches]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* show_matches: show the content that matched (default: false)
\x1b[1mEXAMPLES\x1b[0m
> grep / unbound true
/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin
/copy/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin | 11.284811 | 6.970368 | 1.618969 |
self.grep(params.path, params.content, re.IGNORECASE, params.show_matches) | def do_igrep(self, params) | \x1b[1mNAME\x1b[0m
igrep - Prints znodes with a value matching the given text (ignoring case)
\x1b[1mSYNOPSIS\x1b[0m
igrep [path] <content> [show_matches]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* show_matches: show the content that matched (default: false)
\x1b[1mEXAMPLES\x1b[0m
> igrep / UNBound true
/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin
/copy/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin | 9.7123 | 5.599004 | 1.734648 |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
value, _ = self._zk.get(params.path, **kwargs)
# maybe it's compressed?
if value is not None:
try:
value = zlib.decompress(value)
except:
pass
self.show_output(value) | def do_get(self, params) | \x1b[1mNAME\x1b[0m
get - Gets the znode's value
\x1b[1mSYNOPSIS\x1b[0m
get <path> [watch]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
> get /foo
bar
# sets a watch
> get /foo true
bar
# trigger the watch
> set /foo 'notbar'
WatchedEvent(type='CHANGED', state='CONNECTED', path=u'/foo') | 5.06896 | 4.821737 | 1.051272 |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
pretty = params.pretty_date
path = self.resolve_path(params.path)
stat = self._zk.exists(path, **kwargs)
if stat:
session = stat.ephemeralOwner if stat.ephemeralOwner else 0
self.show_output("Stat(")
self.show_output(" czxid=0x%x", stat.czxid)
self.show_output(" mzxid=0x%x", stat.mzxid)
self.show_output(" ctime=%s", time.ctime(stat.created) if pretty else stat.ctime)
self.show_output(" mtime=%s", time.ctime(stat.last_modified) if pretty else stat.mtime)
self.show_output(" version=%s", stat.version)
self.show_output(" cversion=%s", stat.cversion)
self.show_output(" aversion=%s", stat.aversion)
self.show_output(" ephemeralOwner=0x%x", session)
self.show_output(" dataLength=%s", stat.dataLength)
self.show_output(" numChildren=%s", stat.numChildren)
self.show_output(" pzxid=0x%x", stat.pzxid)
self.show_output(")")
else:
self.show_output("Path %s doesn't exist", params.path) | def do_exists(self, params) | \x1b[1mNAME\x1b[0m
exists - Gets the znode's stat information
\x1b[1mSYNOPSIS\x1b[0m
exists <path> [watch] [pretty_date]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (data) watch on the path (default: false)
\x1b[1mEXAMPLES\x1b[0m
exists /foo
Stat(
czxid=101,
mzxid=102,
ctime=1382820644375,
mtime=1382820693801,
version=1,
cversion=0,
aversion=0,
ephemeralOwner=0,
dataLength=6,
numChildren=0,
pzxid=101
)
# sets a watch
> exists /foo true
...
# trigger the watch
> rm /foo
WatchedEvent(type='DELETED', state='CONNECTED', path=u'/foo') | 2.138582 | 1.846613 | 1.158111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.