repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
ggaughan/pipe2py
pipe2py/modules/pipesubstr.py
asyncPipeSubstr
def asyncPipeSubstr(context=None, _INPUT=None, conf=None, **kwargs): """A string module that asynchronously returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of substrings """ conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = yield asyncStarMap(partial(maybeDeferred, parse_result), parsed) returnValue(iter(_OUTPUT))
python
def asyncPipeSubstr(context=None, _INPUT=None, conf=None, **kwargs): """A string module that asynchronously returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of substrings """ conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = yield asyncStarMap(partial(maybeDeferred, parse_result), parsed) returnValue(iter(_OUTPUT))
A string module that asynchronously returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of substrings
https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/modules/pipesubstr.py#L31-L51
ggaughan/pipe2py
pipe2py/modules/pipesubstr.py
pipe_substr
def pipe_substr(context=None, _INPUT=None, conf=None, **kwargs): """A string module that returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } Returns ------- _OUTPUT : generator of substrings """ conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
python
def pipe_substr(context=None, _INPUT=None, conf=None, **kwargs): """A string module that returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } Returns ------- _OUTPUT : generator of substrings """ conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
A string module that returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } Returns ------- _OUTPUT : generator of substrings
https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/modules/pipesubstr.py#L55-L75
bwesterb/py-seccure
src/__init__.py
serialize_number
def serialize_number(x, fmt=SER_BINARY, outlen=None): """ Serializes `x' to a string of length `outlen' in format `fmt' """ ret = b'' if fmt == SER_BINARY: while x: x, r = divmod(x, 256) ret = six.int2byte(int(r)) + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, b'\0') return ret assert fmt == SER_COMPACT while x: x, r = divmod(x, len(COMPACT_DIGITS)) ret = COMPACT_DIGITS[r:r + 1] + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, COMPACT_DIGITS[0:1]) return ret
python
def serialize_number(x, fmt=SER_BINARY, outlen=None): """ Serializes `x' to a string of length `outlen' in format `fmt' """ ret = b'' if fmt == SER_BINARY: while x: x, r = divmod(x, 256) ret = six.int2byte(int(r)) + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, b'\0') return ret assert fmt == SER_COMPACT while x: x, r = divmod(x, len(COMPACT_DIGITS)) ret = COMPACT_DIGITS[r:r + 1] + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, COMPACT_DIGITS[0:1]) return ret
Serializes `x' to a string of length `outlen' in format `fmt'
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L57-L75
bwesterb/py-seccure
src/__init__.py
deserialize_number
def deserialize_number(s, fmt=SER_BINARY): """ Deserializes a number from a string `s' in format `fmt' """ ret = gmpy.mpz(0) if fmt == SER_BINARY: if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") for c in s: ret *= 256 ret += byte2int(c) return ret assert fmt == SER_COMPACT if isinstance(s, six.text_type): s = s.encode('ascii') for c in s: ret *= len(COMPACT_DIGITS) ret += R_COMPACT_DIGITS[c] return ret
python
def deserialize_number(s, fmt=SER_BINARY): """ Deserializes a number from a string `s' in format `fmt' """ ret = gmpy.mpz(0) if fmt == SER_BINARY: if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") for c in s: ret *= 256 ret += byte2int(c) return ret assert fmt == SER_COMPACT if isinstance(s, six.text_type): s = s.encode('ascii') for c in s: ret *= len(COMPACT_DIGITS) ret += R_COMPACT_DIGITS[c] return ret
Deserializes a number from a string `s' in format `fmt'
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L78-L96
bwesterb/py-seccure
src/__init__.py
mod_issquare
def mod_issquare(a, p): """ Returns whether `a' is a square modulo p """ if not a: return True p1 = p // 2 p2 = pow(a, p1, p) return p2 == 1
python
def mod_issquare(a, p): """ Returns whether `a' is a square modulo p """ if not a: return True p1 = p // 2 p2 = pow(a, p1, p) return p2 == 1
Returns whether `a' is a square modulo p
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L113-L119
bwesterb/py-seccure
src/__init__.py
mod_root
def mod_root(a, p): """ Return a root of `a' modulo p """ if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> 1 b = pow(a, h, p) x = (a * b) % p b = (b * x) % p while b != 1: h = (b * b) % p m = 1 while h != 1: h = (h * h) % p m += 1 h = gmpy.mpz(0) h = h.setbit(r - m - 1) t = pow(y, h, p) y = (t * t) % p r = m x = (x * t) % p b = (b * y) % p return x
python
def mod_root(a, p): """ Return a root of `a' modulo p """ if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> 1 b = pow(a, h, p) x = (a * b) % p b = (b * x) % p while b != 1: h = (b * b) % p m = 1 while h != 1: h = (h * h) % p m += 1 h = gmpy.mpz(0) h = h.setbit(r - m - 1) t = pow(y, h, p) y = (t * t) % p r = m x = (x * t) % p b = (b * y) % p return x
Return a root of `a' modulo p
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L122-L154
bwesterb/py-seccure
src/__init__.py
encrypt
def encrypt(s, pk, pk_format=SER_COMPACT, mac_bytes=10, curve=None): """ Encrypts `s' for public key `pk' """ curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.encrypt(s, mac_bytes)
python
def encrypt(s, pk, pk_format=SER_COMPACT, mac_bytes=10, curve=None): """ Encrypts `s' for public key `pk' """ curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.encrypt(s, mac_bytes)
Encrypts `s' for public key `pk'
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L903-L908
bwesterb/py-seccure
src/__init__.py
decrypt
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10): """ Decrypts `s' with passphrase `passphrase' """ curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.decrypt(s, mac_bytes)
python
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10): """ Decrypts `s' with passphrase `passphrase' """ curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.decrypt(s, mac_bytes)
Decrypts `s' with passphrase `passphrase'
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L911-L915
bwesterb/py-seccure
src/__init__.py
encrypt_file
def encrypt_file(in_path_or_file, out_path_or_file, pk, pk_format=SER_COMPACT, mac_bytes=10, chunk_size=4096, curve=None): """ Encrypts `in_file' to `out_file' for pubkey `pk' """ close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb') close_out = True _encrypt_file(in_file, out_file, pk, pk_format, mac_bytes, chunk_size, curve) finally: if close_out: out_file.close() if close_in: in_file.close()
python
def encrypt_file(in_path_or_file, out_path_or_file, pk, pk_format=SER_COMPACT, mac_bytes=10, chunk_size=4096, curve=None): """ Encrypts `in_file' to `out_file' for pubkey `pk' """ close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb') close_out = True _encrypt_file(in_file, out_file, pk, pk_format, mac_bytes, chunk_size, curve) finally: if close_out: out_file.close() if close_in: in_file.close()
Encrypts `in_file' to `out_file' for pubkey `pk'
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L918-L936
bwesterb/py-seccure
src/__init__.py
decrypt_file
def decrypt_file(in_path_or_file, out_path_or_file, passphrase, curve='secp160r1', mac_bytes=10, chunk_size=4096): """ Decrypts `in_file' to `out_file' with passphrase `passphrase' """ close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb') close_out = True _decrypt_file(in_file, out_file, passphrase, curve, mac_bytes, chunk_size) finally: if close_out: out_file.close() if close_in: in_file.close()
python
def decrypt_file(in_path_or_file, out_path_or_file, passphrase, curve='secp160r1', mac_bytes=10, chunk_size=4096): """ Decrypts `in_file' to `out_file' with passphrase `passphrase' """ close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb') close_out = True _decrypt_file(in_file, out_file, passphrase, curve, mac_bytes, chunk_size) finally: if close_out: out_file.close() if close_in: in_file.close()
Decrypts `in_file' to `out_file' with passphrase `passphrase'
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L939-L957
bwesterb/py-seccure
src/__init__.py
verify
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT, curve=None): """ Verifies that `sig' is a signature of pubkey `pk' for the message `s'. """ if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.verify(hashlib.sha512(s).digest(), sig, sig_format)
python
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT, curve=None): """ Verifies that `sig' is a signature of pubkey `pk' for the message `s'. """ if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.verify(hashlib.sha512(s).digest(), sig, sig_format)
Verifies that `sig' is a signature of pubkey `pk' for the message `s'.
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L985-L995
bwesterb/py-seccure
src/__init__.py
sign
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1'): """ Signs `s' with passphrase `passphrase' """ if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.sign(hashlib.sha512(s).digest(), sig_format)
python
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1'): """ Signs `s' with passphrase `passphrase' """ if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.sign(hashlib.sha512(s).digest(), sig_format)
Signs `s' with passphrase `passphrase'
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L998-L1005
bwesterb/py-seccure
src/__init__.py
generate_keypair
def generate_keypair(curve='secp160r1', randfunc=None): """ Convenience function to generate a random new keypair (passphrase, pubkey). """ if randfunc is None: randfunc = Crypto.Random.new().read curve = Curve.by_name(curve) raw_privkey = randfunc(curve.order_len_bin) privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT) pubkey = str(passphrase_to_pubkey(privkey)) return (privkey, pubkey)
python
def generate_keypair(curve='secp160r1', randfunc=None): """ Convenience function to generate a random new keypair (passphrase, pubkey). """ if randfunc is None: randfunc = Crypto.Random.new().read curve = Curve.by_name(curve) raw_privkey = randfunc(curve.order_len_bin) privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT) pubkey = str(passphrase_to_pubkey(privkey)) return (privkey, pubkey)
Convenience function to generate a random new keypair (passphrase, pubkey).
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L1013-L1022
bwesterb/py-seccure
src/__init__.py
PubKey.verify
def verify(self, h, sig, sig_fmt=SER_BINARY): """ Verifies that `sig' is a signature for a message with SHA-512 hash `h'. """ s = deserialize_number(sig, sig_fmt) return self.p._ECDSA_verify(h, s)
python
def verify(self, h, sig, sig_fmt=SER_BINARY): """ Verifies that `sig' is a signature for a message with SHA-512 hash `h'. """ s = deserialize_number(sig, sig_fmt) return self.p._ECDSA_verify(h, s)
Verifies that `sig' is a signature for a message with SHA-512 hash `h'.
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L597-L601
bwesterb/py-seccure
src/__init__.py
PubKey.encrypt_to
def encrypt_to(self, f, mac_bytes=10): """ Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'. """ ctx = EncryptionContext(f, self.p, mac_bytes) yield ctx ctx.finish()
python
def encrypt_to(self, f, mac_bytes=10): """ Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'. """ ctx = EncryptionContext(f, self.p, mac_bytes) yield ctx ctx.finish()
Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'.
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L604-L609
bwesterb/py-seccure
src/__init__.py
PubKey.encrypt
def encrypt(self, s, mac_bytes=10): """ Encrypt `s' for this pubkey. """ if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with self.encrypt_to(out, mac_bytes) as f: f.write(s) return out.getvalue()
python
def encrypt(self, s, mac_bytes=10): """ Encrypt `s' for this pubkey. """ if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with self.encrypt_to(out, mac_bytes) as f: f.write(s) return out.getvalue()
Encrypt `s' for this pubkey.
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L611-L620
bwesterb/py-seccure
src/__init__.py
PrivKey.decrypt_from
def decrypt_from(self, f, mac_bytes=10): """ Decrypts a message from f. """ ctx = DecryptionContext(self.curve, f, self, mac_bytes) yield ctx ctx.read()
python
def decrypt_from(self, f, mac_bytes=10): """ Decrypts a message from f. """ ctx = DecryptionContext(self.curve, f, self, mac_bytes) yield ctx ctx.read()
Decrypts a message from f.
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L643-L647
bwesterb/py-seccure
src/__init__.py
PrivKey.sign
def sign(self, h, sig_format=SER_BINARY): """ Signs the message with SHA-512 hash `h' with this private key. """ outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT else self.curve.sig_len_bin) sig = self._ECDSA_sign(h) return serialize_number(sig, sig_format, outlen)
python
def sign(self, h, sig_format=SER_BINARY): """ Signs the message with SHA-512 hash `h' with this private key. """ outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT else self.curve.sig_len_bin) sig = self._ECDSA_sign(h) return serialize_number(sig, sig_format, outlen)
Signs the message with SHA-512 hash `h' with this private key.
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L656-L661
bwesterb/py-seccure
src/__init__.py
Curve.hash_to_exponent
def hash_to_exponent(self, h): """ Converts a 32 byte hash to an exponent """ ctr = Crypto.Util.Counter.new(128, initial_value=0) cipher = Crypto.Cipher.AES.new(h, Crypto.Cipher.AES.MODE_CTR, counter=ctr) buf = cipher.encrypt(b'\0' * self.order_len_bin) return self._buf_to_exponent(buf)
python
def hash_to_exponent(self, h): """ Converts a 32 byte hash to an exponent """ ctr = Crypto.Util.Counter.new(128, initial_value=0) cipher = Crypto.Cipher.AES.new(h, Crypto.Cipher.AES.MODE_CTR, counter=ctr) buf = cipher.encrypt(b'\0' * self.order_len_bin) return self._buf_to_exponent(buf)
Converts a 32 byte hash to an exponent
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L859-L865
DomainTools/python_api
domaintools/cli.py
parse
def parse(args=None): """Defines how to parse CLI arguments for the DomainTools API""" parser = argparse.ArgumentParser(description='The DomainTools CLI API Client') parser.add_argument('-u', '--username', dest='user', default='', help='API Username') parser.add_argument('-k', '--key', dest='key', default='', help='API Key') parser.add_argument('-c', '--credfile', dest='credentials', default=os.path.expanduser('~/.dtapi'), help='Optional file with API username and API key, one per line.') parser.add_argument('-l', '--rate-limit', dest='rate_limit', action='store_true', default=False, help='Rate limit API calls against the API based on per minute limits.') parser.add_argument('-f', '--format', dest='format', choices=['list', 'json', 'xml', 'html'], default='json') parser.add_argument('-o', '--outfile', dest='out_file', type=argparse.FileType('wbU'), default=sys.stdout, help='Output file (defaults to stdout)') parser.add_argument('-v', '--version', action='version', version='DomainTools CLI API Client {0}'.format(version)) parser.add_argument('--no-https', dest='https', action='store_false', default=True, help='Use HTTP instead of HTTPS.') parser.add_argument('--no-verify-ssl', dest='verify_ssl', action='store_false', default=True, help='Skip verification of SSL certificate when making HTTPs API calls') subparsers = parser.add_subparsers(help='The name of the API call you wish to perform (`whois` for example)', dest='api_call') subparsers.required = True for api_call in API_CALLS: api_method = getattr(API, api_call) subparser = subparsers.add_parser(api_call, help=api_method.__name__) spec = inspect.getargspec(api_method) for argument_name, default in reversed(list(zip_longest(reversed(spec.args or []), reversed(spec.defaults or []), fillvalue='EMPTY'))): if argument_name == 'self': continue elif default == 'EMPTY': subparser.add_argument(argument_name) else: subparser.add_argument('--{0}'.format(argument_name.replace('_', '-')), dest=argument_name, default=default, nargs='*') arguments = vars(parser.parse_args(args) if args else parser.parse_args()) if not arguments.get('user', None) or not arguments.get('key', None): try: with open(arguments.pop('credentials')) as credentials: arguments['user'], arguments['key'] = credentials.readline().strip(), credentials.readline().strip() except Exception: pass for key, value in arguments.items(): if value in ('-', ['-']): arguments[key] == (line.strip() for line in sys.stdin.readlines()) elif value == []: arguments[key] = True elif type(value) == list and len(value) == 1: arguments[key] = value[0] return (arguments.pop('out_file'), arguments.pop('format'), arguments)
python
def parse(args=None): """Defines how to parse CLI arguments for the DomainTools API""" parser = argparse.ArgumentParser(description='The DomainTools CLI API Client') parser.add_argument('-u', '--username', dest='user', default='', help='API Username') parser.add_argument('-k', '--key', dest='key', default='', help='API Key') parser.add_argument('-c', '--credfile', dest='credentials', default=os.path.expanduser('~/.dtapi'), help='Optional file with API username and API key, one per line.') parser.add_argument('-l', '--rate-limit', dest='rate_limit', action='store_true', default=False, help='Rate limit API calls against the API based on per minute limits.') parser.add_argument('-f', '--format', dest='format', choices=['list', 'json', 'xml', 'html'], default='json') parser.add_argument('-o', '--outfile', dest='out_file', type=argparse.FileType('wbU'), default=sys.stdout, help='Output file (defaults to stdout)') parser.add_argument('-v', '--version', action='version', version='DomainTools CLI API Client {0}'.format(version)) parser.add_argument('--no-https', dest='https', action='store_false', default=True, help='Use HTTP instead of HTTPS.') parser.add_argument('--no-verify-ssl', dest='verify_ssl', action='store_false', default=True, help='Skip verification of SSL certificate when making HTTPs API calls') subparsers = parser.add_subparsers(help='The name of the API call you wish to perform (`whois` for example)', dest='api_call') subparsers.required = True for api_call in API_CALLS: api_method = getattr(API, api_call) subparser = subparsers.add_parser(api_call, help=api_method.__name__) spec = inspect.getargspec(api_method) for argument_name, default in reversed(list(zip_longest(reversed(spec.args or []), reversed(spec.defaults or []), fillvalue='EMPTY'))): if argument_name == 'self': continue elif default == 'EMPTY': subparser.add_argument(argument_name) else: subparser.add_argument('--{0}'.format(argument_name.replace('_', '-')), dest=argument_name, default=default, nargs='*') arguments = vars(parser.parse_args(args) if args else parser.parse_args()) if not arguments.get('user', None) or not arguments.get('key', None): try: with open(arguments.pop('credentials')) as credentials: arguments['user'], arguments['key'] = credentials.readline().strip(), credentials.readline().strip() except Exception: pass for key, value in arguments.items(): if value in ('-', ['-']): arguments[key] == (line.strip() for line in sys.stdin.readlines()) elif value == []: arguments[key] = True elif type(value) == list and len(value) == 1: arguments[key] = value[0] return (arguments.pop('out_file'), arguments.pop('format'), arguments)
Defines how to parse CLI arguments for the DomainTools API
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/cli.py#L19-L71
DomainTools/python_api
domaintools/cli.py
run
def run(): # pragma: no cover """Defines how to start the CLI for the DomainTools API""" out_file, out_format, arguments = parse() user, key = arguments.pop('user', None), arguments.pop('key', None) if not user or not key: sys.stderr.write('Credentials are required to perform API calls.\n') sys.exit(1) api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'), rate_limit=arguments.pop('rate_limit')) response = getattr(api, arguments.pop('api_call'))(**arguments) output = str(getattr(response, out_format) if out_format != 'list' else response.as_list()) out_file.write(output if output.endswith('\n') else output + '\n')
python
def run(): # pragma: no cover """Defines how to start the CLI for the DomainTools API""" out_file, out_format, arguments = parse() user, key = arguments.pop('user', None), arguments.pop('key', None) if not user or not key: sys.stderr.write('Credentials are required to perform API calls.\n') sys.exit(1) api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'), rate_limit=arguments.pop('rate_limit')) response = getattr(api, arguments.pop('api_call'))(**arguments) output = str(getattr(response, out_format) if out_format != 'list' else response.as_list()) out_file.write(output if output.endswith('\n') else output + '\n')
Defines how to start the CLI for the DomainTools API
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/cli.py#L74-L86
jazzband/django-authority
authority/decorators.py
permission_required
def permission_required(perm, *lookup_variables, **kwargs): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. """ login_url = kwargs.pop('login_url', settings.LOGIN_URL) redirect_field_name = kwargs.pop('redirect_field_name', REDIRECT_FIELD_NAME) redirect_to_login = kwargs.pop('redirect_to_login', True) def decorate(view_func): def decorated(request, *args, **kwargs): if request.user.is_authenticated(): params = [] for lookup_variable in lookup_variables: if isinstance(lookup_variable, string_types): value = kwargs.get(lookup_variable, None) if value is None: continue params.append(value) elif isinstance(lookup_variable, (tuple, list)): model, lookup, varname = lookup_variable value = kwargs.get(varname, None) if value is None: continue if isinstance(model, string_types): model_class = apps.get_model(*model.split(".")) else: model_class = model if model_class is None: raise ValueError( "The given argument '%s' is not a valid model." % model) if (inspect.isclass(model_class) and not issubclass(model_class, Model)): raise ValueError( 'The argument %s needs to be a model.' % model) obj = get_object_or_404(model_class, **{lookup: value}) params.append(obj) check = get_check(request.user, perm) granted = False if check is not None: granted = check(*params) if granted or request.user.has_perm(perm): return view_func(request, *args, **kwargs) if redirect_to_login: path = urlquote(request.get_full_path()) tup = login_url, redirect_field_name, path return HttpResponseRedirect('%s?%s=%s' % tup) return permission_denied(request) return wraps(view_func)(decorated) return decorate
python
def permission_required(perm, *lookup_variables, **kwargs): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. """ login_url = kwargs.pop('login_url', settings.LOGIN_URL) redirect_field_name = kwargs.pop('redirect_field_name', REDIRECT_FIELD_NAME) redirect_to_login = kwargs.pop('redirect_to_login', True) def decorate(view_func): def decorated(request, *args, **kwargs): if request.user.is_authenticated(): params = [] for lookup_variable in lookup_variables: if isinstance(lookup_variable, string_types): value = kwargs.get(lookup_variable, None) if value is None: continue params.append(value) elif isinstance(lookup_variable, (tuple, list)): model, lookup, varname = lookup_variable value = kwargs.get(varname, None) if value is None: continue if isinstance(model, string_types): model_class = apps.get_model(*model.split(".")) else: model_class = model if model_class is None: raise ValueError( "The given argument '%s' is not a valid model." % model) if (inspect.isclass(model_class) and not issubclass(model_class, Model)): raise ValueError( 'The argument %s needs to be a model.' % model) obj = get_object_or_404(model_class, **{lookup: value}) params.append(obj) check = get_check(request.user, perm) granted = False if check is not None: granted = check(*params) if granted or request.user.has_perm(perm): return view_func(request, *args, **kwargs) if redirect_to_login: path = urlquote(request.get_full_path()) tup = login_url, redirect_field_name, path return HttpResponseRedirect('%s?%s=%s' % tup) return permission_denied(request) return wraps(view_func)(decorated) return decorate
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/decorators.py#L16-L65
jazzband/django-authority
authority/decorators.py
permission_required_or_403
def permission_required_or_403(perm, *args, **kwargs): """ Decorator that wraps the permission_required decorator and returns a permission denied (403) page instead of redirecting to the login URL. """ kwargs['redirect_to_login'] = False return permission_required(perm, *args, **kwargs)
python
def permission_required_or_403(perm, *args, **kwargs): """ Decorator that wraps the permission_required decorator and returns a permission denied (403) page instead of redirecting to the login URL. """ kwargs['redirect_to_login'] = False return permission_required(perm, *args, **kwargs)
Decorator that wraps the permission_required decorator and returns a permission denied (403) page instead of redirecting to the login URL.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/decorators.py#L68-L74
jazzband/django-authority
authority/templatetags/permissions.py
get_permissions
def get_permissions(parser, token): """ Retrieves all permissions associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permissions obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permissions obj as "my_permissions" %} {% get_permissions obj for request.user as "my_permissions" %} """ return PermissionsForObjectNode.handle_token(parser, token, approved=True, name='"permissions"')
python
def get_permissions(parser, token): """ Retrieves all permissions associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permissions obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permissions obj as "my_permissions" %} {% get_permissions obj for request.user as "my_permissions" %} """ return PermissionsForObjectNode.handle_token(parser, token, approved=True, name='"permissions"')
Retrieves all permissions associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permissions obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permissions obj as "my_permissions" %} {% get_permissions obj for request.user as "my_permissions" %}
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L263-L280
jazzband/django-authority
authority/templatetags/permissions.py
get_permission_requests
def get_permission_requests(parser, token): """ Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission_requests obj as "my_permissions" %} {% get_permission_requests obj for request.user as "my_permissions" %} """ return PermissionsForObjectNode.handle_token(parser, token, approved=False, name='"permission_requests"')
python
def get_permission_requests(parser, token): """ Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission_requests obj as "my_permissions" %} {% get_permission_requests obj for request.user as "my_permissions" %} """ return PermissionsForObjectNode.handle_token(parser, token, approved=False, name='"permission_requests"')
Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission_requests obj as "my_permissions" %} {% get_permission_requests obj for request.user as "my_permissions" %}
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L284-L302
jazzband/django-authority
authority/templatetags/permissions.py
get_permission
def get_permission(parser, token): """ Performs a permission check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission "poll_permission.change_poll" for request.user and poll as "is_allowed" %} {% get_permission "poll_permission.change_poll" for request.user and poll,second_poll as "is_allowed" %} {% if is_allowed %} I've got ze power to change ze pollllllzzz. Muahahaa. {% else %} Meh. No power for meeeee. {% endif %} """ return PermissionForObjectNode.handle_token(parser, token, approved=True, name='"permission"')
python
def get_permission(parser, token): """ Performs a permission check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission "poll_permission.change_poll" for request.user and poll as "is_allowed" %} {% get_permission "poll_permission.change_poll" for request.user and poll,second_poll as "is_allowed" %} {% if is_allowed %} I've got ze power to change ze pollllllzzz. Muahahaa. {% else %} Meh. No power for meeeee. {% endif %} """ return PermissionForObjectNode.handle_token(parser, token, approved=True, name='"permission"')
Performs a permission check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission "poll_permission.change_poll" for request.user and poll as "is_allowed" %} {% get_permission "poll_permission.change_poll" for request.user and poll,second_poll as "is_allowed" %} {% if is_allowed %} I've got ze power to change ze pollllllzzz. Muahahaa. {% else %} Meh. No power for meeeee. {% endif %}
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L349-L372
jazzband/django-authority
authority/templatetags/permissions.py
get_permission_request
def get_permission_request(parser, token): """ Performs a permission request check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission_request "poll_permission.change_poll" for request.user and poll as "asked_for_permissio" %} {% get_permission_request "poll_permission.change_poll" for request.user and poll,second_poll as "asked_for_permissio" %} {% if asked_for_permissio %} Dude, you already asked for permission! {% else %} Oh, please fill out this 20 page form and sign here. {% endif %} """ return PermissionForObjectNode.handle_token( parser, token, approved=False, name='"permission_request"')
python
def get_permission_request(parser, token): """ Performs a permission request check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission_request "poll_permission.change_poll" for request.user and poll as "asked_for_permissio" %} {% get_permission_request "poll_permission.change_poll" for request.user and poll,second_poll as "asked_for_permissio" %} {% if asked_for_permissio %} Dude, you already asked for permission! {% else %} Oh, please fill out this 20 page form and sign here. {% endif %} """ return PermissionForObjectNode.handle_token( parser, token, approved=False, name='"permission_request"')
Performs a permission request check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission_request "poll_permission.change_poll" for request.user and poll as "asked_for_permissio" %} {% get_permission_request "poll_permission.change_poll" for request.user and poll,second_poll as "asked_for_permissio" %} {% if asked_for_permissio %} Dude, you already asked for permission! {% else %} Oh, please fill out this 20 page form and sign here. {% endif %}
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L376-L398
jazzband/django-authority
authority/templatetags/permissions.py
permission_delete_link
def permission_delete_link(context, perm): """ Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): if (user.has_perm('authority.delete_foreign_permissions') or user.pk == perm.creator.pk): return base_link(context, perm, 'authority-delete-permission') return {'url': None}
python
def permission_delete_link(context, perm): """ Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): if (user.has_perm('authority.delete_foreign_permissions') or user.pk == perm.creator.pk): return base_link(context, perm, 'authority-delete-permission') return {'url': None}
Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L409-L420
jazzband/django-authority
authority/templatetags/permissions.py
permission_request_delete_link
def permission_request_delete_link(context, perm): """ Renders a html link to the delete view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): link_kwargs = base_link(context, perm, 'authority-delete-permission-request') if user.has_perm('authority.delete_permission'): link_kwargs['is_requestor'] = False return link_kwargs if not perm.approved and perm.user == user: link_kwargs['is_requestor'] = True return link_kwargs return {'url': None}
python
def permission_request_delete_link(context, perm): """ Renders a html link to the delete view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): link_kwargs = base_link(context, perm, 'authority-delete-permission-request') if user.has_perm('authority.delete_permission'): link_kwargs['is_requestor'] = False return link_kwargs if not perm.approved and perm.user == user: link_kwargs['is_requestor'] = True return link_kwargs return {'url': None}
Renders a html link to the delete view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L424-L440
jazzband/django-authority
authority/templatetags/permissions.py
permission_request_approve_link
def permission_request_approve_link(context, perm): """ Renders a html link to the approve view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): if user.has_perm('authority.approve_permission_requests'): return base_link(context, perm, 'authority-approve-permission-request') return {'url': None}
python
def permission_request_approve_link(context, perm): """ Renders a html link to the approve view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): if user.has_perm('authority.approve_permission_requests'): return base_link(context, perm, 'authority-approve-permission-request') return {'url': None}
Renders a html link to the approve view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L444-L454
jazzband/django-authority
authority/templatetags/permissions.py
ResolverNode.resolve
def resolve(self, var, context): """Resolves a variable out of context if it's not in quotes""" if var is None: return var if var[0] in ('"', "'") and var[-1] == var[0]: return var[1:-1] else: return template.Variable(var).resolve(context)
python
def resolve(self, var, context): """Resolves a variable out of context if it's not in quotes""" if var is None: return var if var[0] in ('"', "'") and var[-1] == var[0]: return var[1:-1] else: return template.Variable(var).resolve(context)
Resolves a variable out of context if it's not in quotes
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/templatetags/permissions.py#L40-L47
jazzband/django-authority
authority/managers.py
PermissionManager.group_permissions
def group_permissions(self, group, perm, obj, approved=True): """ Get objects that have Group perm permission on """ return self.get_for_model(obj).select_related( 'user', 'group', 'creator').filter(group=group, codename=perm, approved=approved)
python
def group_permissions(self, group, perm, obj, approved=True): """ Get objects that have Group perm permission on """ return self.get_for_model(obj).select_related( 'user', 'group', 'creator').filter(group=group, codename=perm, approved=approved)
Get objects that have Group perm permission on
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/managers.py#L48-L54
jazzband/django-authority
authority/managers.py
PermissionManager.delete_user_permissions
def delete_user_permissions(self, user, perm, obj, check_groups=False): """ Remove granular permission perm from user on an object instance """ user_perms = self.user_permissions(user, perm, obj, check_groups=False) if not user_perms.filter(object_id=obj.id): return perms = self.user_permissions(user, perm, obj).filter(object_id=obj.id) perms.delete()
python
def delete_user_permissions(self, user, perm, obj, check_groups=False): """ Remove granular permission perm from user on an object instance """ user_perms = self.user_permissions(user, perm, obj, check_groups=False) if not user_perms.filter(object_id=obj.id): return perms = self.user_permissions(user, perm, obj).filter(object_id=obj.id) perms.delete()
Remove granular permission perm from user on an object instance
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/managers.py#L63-L71
DomainTools/python_api
domaintools/results.py
ParsedWhois.flattened
def flattened(self): """Returns a flattened version of the parsed whois data""" parsed = self['parsed_whois'] flat = OrderedDict() for key in ('domain', 'created_date', 'updated_date', 'expired_date', 'statuses', 'name_servers'): value = parsed[key] flat[key] = ' | '.join(value) if type(value) in (list, tuple) else value registrar = parsed.get('registrar', {}) for key in ('name', 'abuse_contact_phone', 'abuse_contact_email', 'iana_id', 'url', 'whois_server'): flat['registrar_{0}'.format(key)] = registrar[key] for contact_type in ('registrant', 'admin', 'tech', 'billing'): contact = parsed.get('contacts', {}).get(contact_type, {}) for key in ('name', 'email', 'org', 'street', 'city', 'state', 'postal', 'country', 'phone', 'fax'): value = contact[key] flat['{0}_{1}'.format(contact_type, key)] = ' '.join(value) if type(value) in (list, tuple) else value return flat
python
def flattened(self): """Returns a flattened version of the parsed whois data""" parsed = self['parsed_whois'] flat = OrderedDict() for key in ('domain', 'created_date', 'updated_date', 'expired_date', 'statuses', 'name_servers'): value = parsed[key] flat[key] = ' | '.join(value) if type(value) in (list, tuple) else value registrar = parsed.get('registrar', {}) for key in ('name', 'abuse_contact_phone', 'abuse_contact_email', 'iana_id', 'url', 'whois_server'): flat['registrar_{0}'.format(key)] = registrar[key] for contact_type in ('registrant', 'admin', 'tech', 'billing'): contact = parsed.get('contacts', {}).get(contact_type, {}) for key in ('name', 'email', 'org', 'street', 'city', 'state', 'postal', 'country', 'phone', 'fax'): value = contact[key] flat['{0}_{1}'.format(contact_type, key)] = ' '.join(value) if type(value) in (list, tuple) else value return flat
Returns a flattened version of the parsed whois data
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/results.py#L50-L68
jazzband/django-authority
authority/views.py
permission_denied
def permission_denied(request, template_name=None, extra_context=None): """ Default 403 handler. Templates: `403.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ if template_name is None: template_name = ('403.html', 'authority/403.html') context = { 'request_path': request.path, } if extra_context: context.update(extra_context) return HttpResponseForbidden(loader.render_to_string( template_name=template_name, context=context, request=request, ))
python
def permission_denied(request, template_name=None, extra_context=None): """ Default 403 handler. Templates: `403.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ if template_name is None: template_name = ('403.html', 'authority/403.html') context = { 'request_path': request.path, } if extra_context: context.update(extra_context) return HttpResponseForbidden(loader.render_to_string( template_name=template_name, context=context, request=request, ))
Default 403 handler. Templates: `403.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/')
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/views.py#L96-L116
jazzband/django-authority
authority/models.py
Permission.approve
def approve(self, creator): """ Approve granular permission request setting a Permission entry as approved=True for a specific action from an user on an object instance. """ self.approved = True self.creator = creator self.save()
python
def approve(self, creator): """ Approve granular permission request setting a Permission entry as approved=True for a specific action from an user on an object instance. """ self.approved = True self.creator = creator self.save()
Approve granular permission request setting a Permission entry as approved=True for a specific action from an user on an object instance.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/models.py#L59-L66
jazzband/django-authority
authority/utils.py
autodiscover_modules
def autodiscover_modules(): """ Goes and imports the permissions submodule of every app in INSTALLED_APPS to make sure the permission set classes are registered correctly. """ import imp from django.conf import settings for app in settings.INSTALLED_APPS: try: __import__(app) app_path = sys.modules[app].__path__ except AttributeError: continue try: imp.find_module('permissions', app_path) except ImportError: continue __import__("%s.permissions" % app) app_path = sys.modules["%s.permissions" % app] LOADING = False
python
def autodiscover_modules(): """ Goes and imports the permissions submodule of every app in INSTALLED_APPS to make sure the permission set classes are registered correctly. """ import imp from django.conf import settings for app in settings.INSTALLED_APPS: try: __import__(app) app_path = sys.modules[app].__path__ except AttributeError: continue try: imp.find_module('permissions', app_path) except ImportError: continue __import__("%s.permissions" % app) app_path = sys.modules["%s.permissions" % app] LOADING = False
Goes and imports the permissions submodule of every app in INSTALLED_APPS to make sure the permission set classes are registered correctly.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/utils.py#L6-L26
jazzband/django-authority
authority/permissions.py
BasePermission._get_user_cached_perms
def _get_user_cached_perms(self): """ Set up both the user and group caches. """ if not self.user: return {}, {} group_pks = set(self.user.groups.values_list( 'pk', flat=True, )) perms = Permission.objects.filter( Q(user__pk=self.user.pk) | Q(group__pk__in=group_pks), ) user_permissions = {} group_permissions = {} for perm in perms: if perm.user_id == self.user.pk: user_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True # If the user has the permission do for something, but perm.user != # self.user then by definition that permission came from the # group. else: group_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True return user_permissions, group_permissions
python
def _get_user_cached_perms(self): """ Set up both the user and group caches. """ if not self.user: return {}, {} group_pks = set(self.user.groups.values_list( 'pk', flat=True, )) perms = Permission.objects.filter( Q(user__pk=self.user.pk) | Q(group__pk__in=group_pks), ) user_permissions = {} group_permissions = {} for perm in perms: if perm.user_id == self.user.pk: user_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True # If the user has the permission do for something, but perm.user != # self.user then by definition that permission came from the # group. else: group_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True return user_permissions, group_permissions
Set up both the user and group caches.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L45-L78
jazzband/django-authority
authority/permissions.py
BasePermission._get_group_cached_perms
def _get_group_cached_perms(self): """ Set group cache. """ if not self.group: return {} perms = Permission.objects.filter( group=self.group, ) group_permissions = {} for perm in perms: group_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True return group_permissions
python
def _get_group_cached_perms(self): """ Set group cache. """ if not self.group: return {} perms = Permission.objects.filter( group=self.group, ) group_permissions = {} for perm in perms: group_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True return group_permissions
Set group cache.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L80-L97
jazzband/django-authority
authority/permissions.py
BasePermission._prime_user_perm_caches
def _prime_user_perm_caches(self): """ Prime both the user and group caches and put them on the ``self.user``. In addition add a cache filled flag on ``self.user``. """ perm_cache, group_perm_cache = self._get_user_cached_perms() self.user._authority_perm_cache = perm_cache self.user._authority_group_perm_cache = group_perm_cache self.user._authority_perm_cache_filled = True
python
def _prime_user_perm_caches(self): """ Prime both the user and group caches and put them on the ``self.user``. In addition add a cache filled flag on ``self.user``. """ perm_cache, group_perm_cache = self._get_user_cached_perms() self.user._authority_perm_cache = perm_cache self.user._authority_group_perm_cache = group_perm_cache self.user._authority_perm_cache_filled = True
Prime both the user and group caches and put them on the ``self.user``. In addition add a cache filled flag on ``self.user``.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L99-L107
jazzband/django-authority
authority/permissions.py
BasePermission._prime_group_perm_caches
def _prime_group_perm_caches(self): """ Prime the group cache and put them on the ``self.group``. In addition add a cache filled flag on ``self.group``. """ perm_cache = self._get_group_cached_perms() self.group._authority_perm_cache = perm_cache self.group._authority_perm_cache_filled = True
python
def _prime_group_perm_caches(self): """ Prime the group cache and put them on the ``self.group``. In addition add a cache filled flag on ``self.group``. """ perm_cache = self._get_group_cached_perms() self.group._authority_perm_cache = perm_cache self.group._authority_perm_cache_filled = True
Prime the group cache and put them on the ``self.group``. In addition add a cache filled flag on ``self.group``.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L109-L116
jazzband/django-authority
authority/permissions.py
BasePermission._user_perm_cache
def _user_perm_cache(self): """ cached_permissions will generate the cache in a lazy fashion. """ # Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but this matches how Django # does it. return self.user._authority_perm_cache # Prime the cache. self._prime_user_perm_caches() return self.user._authority_perm_cache
python
def _user_perm_cache(self): """ cached_permissions will generate the cache in a lazy fashion. """ # Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but this matches how Django # does it. return self.user._authority_perm_cache # Prime the cache. self._prime_user_perm_caches() return self.user._authority_perm_cache
cached_permissions will generate the cache in a lazy fashion.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L119-L138
jazzband/django-authority
authority/permissions.py
BasePermission._group_perm_cache
def _group_perm_cache(self): """ cached_permissions will generate the cache in a lazy fashion. """ # Check to see if the cache has been primed. if not self.group: return {} cache_filled = getattr( self.group, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but this matches how Django # does it. return self.group._authority_perm_cache # Prime the cache. self._prime_group_perm_caches() return self.group._authority_perm_cache
python
def _group_perm_cache(self): """ cached_permissions will generate the cache in a lazy fashion. """ # Check to see if the cache has been primed. if not self.group: return {} cache_filled = getattr( self.group, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but this matches how Django # does it. return self.group._authority_perm_cache # Prime the cache. self._prime_group_perm_caches() return self.group._authority_perm_cache
cached_permissions will generate the cache in a lazy fashion.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L141-L160
jazzband/django-authority
authority/permissions.py
BasePermission._user_group_perm_cache
def _user_group_perm_cache(self): """ cached_permissions will generate the cache in a lazy fashion. """ # Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: return self.user._authority_group_perm_cache # Prime the cache. self._prime_user_perm_caches() return self.user._authority_group_perm_cache
python
def _user_group_perm_cache(self): """ cached_permissions will generate the cache in a lazy fashion. """ # Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: return self.user._authority_group_perm_cache # Prime the cache. self._prime_user_perm_caches() return self.user._authority_group_perm_cache
cached_permissions will generate the cache in a lazy fashion.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L163-L180
jazzband/django-authority
authority/permissions.py
BasePermission.invalidate_permissions_cache
def invalidate_permissions_cache(self): """ In the event that the Permission table is changed during the use of a permission the Permission cache will need to be invalidated and regenerated. By calling this method the invalidation will occur, and the next time the cached_permissions is used the cache will be re-primed. """ if self.user: self.user._authority_perm_cache_filled = False if self.group: self.group._authority_perm_cache_filled = False
python
def invalidate_permissions_cache(self): """ In the event that the Permission table is changed during the use of a permission the Permission cache will need to be invalidated and regenerated. By calling this method the invalidation will occur, and the next time the cached_permissions is used the cache will be re-primed. """ if self.user: self.user._authority_perm_cache_filled = False if self.group: self.group._authority_perm_cache_filled = False
In the event that the Permission table is changed during the use of a permission the Permission cache will need to be invalidated and regenerated. By calling this method the invalidation will occur, and the next time the cached_permissions is used the cache will be re-primed.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L182-L193
jazzband/django-authority
authority/permissions.py
BasePermission.has_group_perms
def has_group_perms(self, perm, obj, approved): """ Check if group has the permission for the given object """ if not self.group: return False if self.use_smart_cache: content_type_pk = Permission.objects.get_content_type(obj).pk def _group_has_perms(cached_perms): # Check to see if the permission is in the cache. return cached_perms.get(( obj.pk, content_type_pk, perm, approved, )) # Check to see if the permission is in the cache. return _group_has_perms(self._group_perm_cache) # Actually hit the DB, no smart cache used. return Permission.objects.group_permissions( self.group, perm, obj, approved, ).filter( object_id=obj.pk, ).exists()
python
def has_group_perms(self, perm, obj, approved): """ Check if group has the permission for the given object """ if not self.group: return False if self.use_smart_cache: content_type_pk = Permission.objects.get_content_type(obj).pk def _group_has_perms(cached_perms): # Check to see if the permission is in the cache. return cached_perms.get(( obj.pk, content_type_pk, perm, approved, )) # Check to see if the permission is in the cache. return _group_has_perms(self._group_perm_cache) # Actually hit the DB, no smart cache used. return Permission.objects.group_permissions( self.group, perm, obj, approved, ).filter( object_id=obj.pk, ).exists()
Check if group has the permission for the given object
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L240-L269
jazzband/django-authority
authority/permissions.py
BasePermission.has_perm
def has_perm(self, perm, obj, check_groups=True, approved=True): """ Check if user has the permission for the given object """ if self.user: if self.has_user_perms(perm, obj, approved, check_groups): return True if self.group: return self.has_group_perms(perm, obj, approved) return False
python
def has_perm(self, perm, obj, check_groups=True, approved=True): """ Check if user has the permission for the given object """ if self.user: if self.has_user_perms(perm, obj, approved, check_groups): return True if self.group: return self.has_group_perms(perm, obj, approved) return False
Check if user has the permission for the given object
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L271-L280
jazzband/django-authority
authority/permissions.py
BasePermission.requested_perm
def requested_perm(self, perm, obj, check_groups=True): """ Check if user requested a permission for the given object """ return self.has_perm(perm, obj, check_groups, False)
python
def requested_perm(self, perm, obj, check_groups=True): """ Check if user requested a permission for the given object """ return self.has_perm(perm, obj, check_groups, False)
Check if user requested a permission for the given object
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L282-L286
jazzband/django-authority
authority/permissions.py
BasePermission.assign
def assign(self, check=None, content_object=None, generic=False): """ Assign a permission to a user. To assign permission for all checks: let check=None. To assign permission for all objects: let content_object=None. If generic is True then "check" will be suffixed with _modelname. """ result = [] if not content_object: content_objects = (self.model,) elif not isinstance(content_object, (list, tuple)): content_objects = (content_object,) else: content_objects = content_object if not check: checks = self.generic_checks + getattr(self, 'checks', []) elif not isinstance(check, (list, tuple)): checks = (check,) else: checks = check for content_object in content_objects: # raise an exception before adding any permission # i think Django does not rollback by default if not isinstance(content_object, (Model, ModelBase)): raise NotAModel(content_object) elif isinstance(content_object, Model) and not content_object.pk: raise UnsavedModelInstance(content_object) content_type = ContentType.objects.get_for_model(content_object) for check in checks: if isinstance(content_object, Model): # make an authority per object permission codename = self.get_codename( check, content_object, generic, ) try: perm = Permission.objects.get( user=self.user, codename=codename, approved=True, content_type=content_type, object_id=content_object.pk, ) except Permission.DoesNotExist: perm = Permission.objects.create( user=self.user, content_object=content_object, codename=codename, approved=True, ) result.append(perm) elif isinstance(content_object, ModelBase): # make a Django permission codename = self.get_django_codename( check, content_object, generic, without_left=True, ) try: perm = DjangoPermission.objects.get(codename=codename) except DjangoPermission.DoesNotExist: name = check if '_' in name: name = name[0:name.find('_')] perm = DjangoPermission( name=name, codename=codename, content_type=content_type, ) perm.save() self.user.user_permissions.add(perm) result.append(perm) return result
python
def assign(self, check=None, content_object=None, generic=False): """ Assign a permission to a user. To assign permission for all checks: let check=None. To assign permission for all objects: let content_object=None. If generic is True then "check" will be suffixed with _modelname. """ result = [] if not content_object: content_objects = (self.model,) elif not isinstance(content_object, (list, tuple)): content_objects = (content_object,) else: content_objects = content_object if not check: checks = self.generic_checks + getattr(self, 'checks', []) elif not isinstance(check, (list, tuple)): checks = (check,) else: checks = check for content_object in content_objects: # raise an exception before adding any permission # i think Django does not rollback by default if not isinstance(content_object, (Model, ModelBase)): raise NotAModel(content_object) elif isinstance(content_object, Model) and not content_object.pk: raise UnsavedModelInstance(content_object) content_type = ContentType.objects.get_for_model(content_object) for check in checks: if isinstance(content_object, Model): # make an authority per object permission codename = self.get_codename( check, content_object, generic, ) try: perm = Permission.objects.get( user=self.user, codename=codename, approved=True, content_type=content_type, object_id=content_object.pk, ) except Permission.DoesNotExist: perm = Permission.objects.create( user=self.user, content_object=content_object, codename=codename, approved=True, ) result.append(perm) elif isinstance(content_object, ModelBase): # make a Django permission codename = self.get_django_codename( check, content_object, generic, without_left=True, ) try: perm = DjangoPermission.objects.get(codename=codename) except DjangoPermission.DoesNotExist: name = check if '_' in name: name = name[0:name.find('_')] perm = DjangoPermission( name=name, codename=codename, content_type=content_type, ) perm.save() self.user.user_permissions.add(perm) result.append(perm) return result
Assign a permission to a user. To assign permission for all checks: let check=None. To assign permission for all objects: let content_object=None. If generic is True then "check" will be suffixed with _modelname.
https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L329-L413
DomainTools/python_api
domaintools/api.py
delimited
def delimited(items, character='|'): """Returns a character delimited version of the provided list as a Python string""" return '|'.join(items) if type(items) in (list, tuple, set) else items
python
def delimited(items, character='|'): """Returns a character delimited version of the provided list as a Python string""" return '|'.join(items) if type(items) in (list, tuple, set) else items
Returns a character delimited version of the provided list as a Python string
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L10-L12
DomainTools/python_api
domaintools/api.py
API._rate_limit
def _rate_limit(self): """Pulls in and enforces the latest rate limits for the specified user""" self.limits_set = True for product in self.account_information(): self.limits[product['id']] = {'interval': timedelta(seconds=60 / float(product['per_minute_limit']))}
python
def _rate_limit(self): """Pulls in and enforces the latest rate limits for the specified user""" self.limits_set = True for product in self.account_information(): self.limits[product['id']] = {'interval': timedelta(seconds=60 / float(product['per_minute_limit']))}
Pulls in and enforces the latest rate limits for the specified user
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L50-L54
DomainTools/python_api
domaintools/api.py
API._results
def _results(self, product, path, cls=Results, **kwargs): """Returns _results for the specified API path with the specified **kwargs parameters""" if product != 'account-information' and self.rate_limit and not self.limits_set and not self.limits: self._rate_limit() uri = '/'.join(('{0}://api.domaintools.com'.format('https' if self.https else 'http'), path.lstrip('/'))) parameters = self.default_parameters.copy() parameters['api_username'] = self.username if self.https: parameters['api_key'] = self.key else: parameters['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') parameters['signature'] = hmac(self.key.encode('utf8'), ''.join([self.username, parameters['timestamp'], path]).encode('utf8'), digestmod=sha1).hexdigest() parameters.update(dict((key, str(value).lower() if value in (True, False) else value) for key, value in kwargs.items() if value is not None)) return cls(self, product, uri, **parameters)
python
def _results(self, product, path, cls=Results, **kwargs): """Returns _results for the specified API path with the specified **kwargs parameters""" if product != 'account-information' and self.rate_limit and not self.limits_set and not self.limits: self._rate_limit() uri = '/'.join(('{0}://api.domaintools.com'.format('https' if self.https else 'http'), path.lstrip('/'))) parameters = self.default_parameters.copy() parameters['api_username'] = self.username if self.https: parameters['api_key'] = self.key else: parameters['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') parameters['signature'] = hmac(self.key.encode('utf8'), ''.join([self.username, parameters['timestamp'], path]).encode('utf8'), digestmod=sha1).hexdigest() parameters.update(dict((key, str(value).lower() if value in (True, False) else value) for key, value in kwargs.items() if value is not None)) return cls(self, product, uri, **parameters)
Returns _results for the specified API path with the specified **kwargs parameters
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L56-L73
DomainTools/python_api
domaintools/api.py
API.brand_monitor
def brand_monitor(self, query, exclude=[], domain_status=None, days_back=None, **kwargs): """Pass in one or more terms as a list or separated by the pipe character ( | )""" return self._results('mark-alert', '/v1/mark-alert', query=delimited(query), exclude=delimited(exclude), domain_status=domain_status, days_back=days_back, items_path=('alerts', ), **kwargs)
python
def brand_monitor(self, query, exclude=[], domain_status=None, days_back=None, **kwargs): """Pass in one or more terms as a list or separated by the pipe character ( | )""" return self._results('mark-alert', '/v1/mark-alert', query=delimited(query), exclude=delimited(exclude), domain_status=domain_status, days_back=days_back, items_path=('alerts', ), **kwargs)
Pass in one or more terms as a list or separated by the pipe character ( | )
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L79-L82
DomainTools/python_api
domaintools/api.py
API.domain_search
def domain_search(self, query, exclude_query=[], max_length=25, min_length=2, has_hyphen=True, has_number=True, active_only=False, deleted_only=False, anchor_left=False, anchor_right=False, page=1, **kwargs): """Each term in the query string must be at least three characters long. Pass in a list or use spaces to separate multiple terms. """ return self._results('domain-search', '/v2/domain-search', query=delimited(query, ' '), exclude_query=delimited(exclude_query, ' '), max_length=max_length, min_length=min_length, has_hyphen=has_hyphen, has_number=has_number, active_only=active_only, deleted_only=deleted_only, anchor_left=anchor_left, anchor_right=anchor_right, page=page, items_path=('results', ), **kwargs)
python
def domain_search(self, query, exclude_query=[], max_length=25, min_length=2, has_hyphen=True, has_number=True, active_only=False, deleted_only=False, anchor_left=False, anchor_right=False, page=1, **kwargs): """Each term in the query string must be at least three characters long. Pass in a list or use spaces to separate multiple terms. """ return self._results('domain-search', '/v2/domain-search', query=delimited(query, ' '), exclude_query=delimited(exclude_query, ' '), max_length=max_length, min_length=min_length, has_hyphen=has_hyphen, has_number=has_number, active_only=active_only, deleted_only=deleted_only, anchor_left=anchor_left, anchor_right=anchor_right, page=page, items_path=('results', ), **kwargs)
Each term in the query string must be at least three characters long. Pass in a list or use spaces to separate multiple terms.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L88-L97
DomainTools/python_api
domaintools/api.py
API.domain_suggestions
def domain_suggestions(self, query, **kwargs): """Passed in name must be at least two characters long. Use a list or spaces to separate multiple terms.""" return self._results('domain-suggestions', '/v1/domain-suggestions', query=delimited(query, ' '), items_path=('suggestions', ), **kwargs)
python
def domain_suggestions(self, query, **kwargs): """Passed in name must be at least two characters long. Use a list or spaces to separate multiple terms.""" return self._results('domain-suggestions', '/v1/domain-suggestions', query=delimited(query, ' '), items_path=('suggestions', ), **kwargs)
Passed in name must be at least two characters long. Use a list or spaces to separate multiple terms.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L99-L102
DomainTools/python_api
domaintools/api.py
API.hosting_history
def hosting_history(self, query, **kwargs): """Returns the hosting history from the given domain name""" return self._results('hosting-history', '/v1/{0}/hosting-history'.format(query), cls=GroupedIterable, **kwargs)
python
def hosting_history(self, query, **kwargs): """Returns the hosting history from the given domain name""" return self._results('hosting-history', '/v1/{0}/hosting-history'.format(query), cls=GroupedIterable, **kwargs)
Returns the hosting history from the given domain name
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L104-L106
DomainTools/python_api
domaintools/api.py
API.ip_monitor
def ip_monitor(self, query, days_back=0, page=1, **kwargs): """Pass in the IP Address you wish to query ( i.e. 199.30.228.112 ).""" return self._results('ip-monitor', '/v1/ip-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
python
def ip_monitor(self, query, days_back=0, page=1, **kwargs): """Pass in the IP Address you wish to query ( i.e. 199.30.228.112 ).""" return self._results('ip-monitor', '/v1/ip-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
Pass in the IP Address you wish to query ( i.e. 199.30.228.112 ).
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L108-L111
DomainTools/python_api
domaintools/api.py
API.ip_registrant_monitor
def ip_registrant_monitor(self, query, days_back=0, search_type="all", server=None, country=None, org=None, page=1, include_total_count=False, **kwargs): """Query based on free text query terms""" return self._results('ip-registrant-monitor', '/v1/ip-registrant-monitor', query=query, days_back=days_back, search_type=search_type, server=server, country=country, org=org, page=page, include_total_count=include_total_count, **kwargs)
python
def ip_registrant_monitor(self, query, days_back=0, search_type="all", server=None, country=None, org=None, page=1, include_total_count=False, **kwargs): """Query based on free text query terms""" return self._results('ip-registrant-monitor', '/v1/ip-registrant-monitor', query=query, days_back=days_back, search_type=search_type, server=server, country=country, org=org, page=page, include_total_count=include_total_count, **kwargs)
Query based on free text query terms
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L113-L118
DomainTools/python_api
domaintools/api.py
API.name_server_monitor
def name_server_monitor(self, query, days_back=0, page=1, **kwargs): """Pass in the hostname of the Name Server you wish to query ( i.e. dynect.net ).""" return self._results('name-server-monitor', '/v1/name-server-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
python
def name_server_monitor(self, query, days_back=0, page=1, **kwargs): """Pass in the hostname of the Name Server you wish to query ( i.e. dynect.net ).""" return self._results('name-server-monitor', '/v1/name-server-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
Pass in the hostname of the Name Server you wish to query ( i.e. dynect.net ).
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L120-L123
DomainTools/python_api
domaintools/api.py
API.parsed_whois
def parsed_whois(self, query, **kwargs): """Pass in a domain name""" return self._results('parsed-whois', '/v1/{0}/whois/parsed'.format(query), cls=ParsedWhois, **kwargs)
python
def parsed_whois(self, query, **kwargs): """Pass in a domain name""" return self._results('parsed-whois', '/v1/{0}/whois/parsed'.format(query), cls=ParsedWhois, **kwargs)
Pass in a domain name
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L125-L127
DomainTools/python_api
domaintools/api.py
API.registrant_monitor
def registrant_monitor(self, query, exclude=[], days_back=0, limit=None, **kwargs): """One or more terms as a Python list or separated by the pipe character ( | ).""" return self._results('registrant-alert', '/v1/registrant-alert', query=delimited(query), exclude=delimited(exclude), days_back=days_back, limit=limit, items_path=('alerts', ), **kwargs)
python
def registrant_monitor(self, query, exclude=[], days_back=0, limit=None, **kwargs): """One or more terms as a Python list or separated by the pipe character ( | ).""" return self._results('registrant-alert', '/v1/registrant-alert', query=delimited(query), exclude=delimited(exclude), days_back=days_back, limit=limit, items_path=('alerts', ), **kwargs)
One or more terms as a Python list or separated by the pipe character ( | ).
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L129-L133
DomainTools/python_api
domaintools/api.py
API.reputation
def reputation(self, query, include_reasons=False, **kwargs): """Pass in a domain name to see its reputation score""" return self._results('reputation', '/v1/reputation', domain=query, include_reasons=include_reasons, cls=Reputation, **kwargs)
python
def reputation(self, query, include_reasons=False, **kwargs): """Pass in a domain name to see its reputation score""" return self._results('reputation', '/v1/reputation', domain=query, include_reasons=include_reasons, cls=Reputation, **kwargs)
Pass in a domain name to see its reputation score
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L135-L138
DomainTools/python_api
domaintools/api.py
API.reverse_ip
def reverse_ip(self, domain=None, limit=None, **kwargs): """Pass in a domain name.""" return self._results('reverse-ip', '/v1/{0}/reverse-ip'.format(domain), limit=limit, **kwargs)
python
def reverse_ip(self, domain=None, limit=None, **kwargs): """Pass in a domain name.""" return self._results('reverse-ip', '/v1/{0}/reverse-ip'.format(domain), limit=limit, **kwargs)
Pass in a domain name.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L140-L142
DomainTools/python_api
domaintools/api.py
API.host_domains
def host_domains(self, ip=None, limit=None, **kwargs): """Pass in an IP address.""" return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs)
python
def host_domains(self, ip=None, limit=None, **kwargs): """Pass in an IP address.""" return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs)
Pass in an IP address.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L144-L146
DomainTools/python_api
domaintools/api.py
API.reverse_ip_whois
def reverse_ip_whois(self, query=None, ip=None, country=None, server=None, include_total_count=False, page=1, **kwargs): """Pass in an IP address or a list of free text query terms.""" if (ip and query) or not (ip or query): raise ValueError('Query or IP Address (but not both) must be defined') return self._results('reverse-ip-whois', '/v1/reverse-ip-whois', query=query, ip=ip, country=country, server=server, include_total_count=include_total_count, page=page, items_path=('records', ), **kwargs)
python
def reverse_ip_whois(self, query=None, ip=None, country=None, server=None, include_total_count=False, page=1, **kwargs): """Pass in an IP address or a list of free text query terms.""" if (ip and query) or not (ip or query): raise ValueError('Query or IP Address (but not both) must be defined') return self._results('reverse-ip-whois', '/v1/reverse-ip-whois', query=query, ip=ip, country=country, server=server, include_total_count=include_total_count, page=page, items_path=('records', ), **kwargs)
Pass in an IP address or a list of free text query terms.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L148-L156
DomainTools/python_api
domaintools/api.py
API.reverse_name_server
def reverse_name_server(self, query, limit=None, **kwargs): """Pass in a domain name or a name server.""" return self._results('reverse-name-server', '/v1/{0}/name-server-domains'.format(query), items_path=('primary_domains', ), limit=limit, **kwargs)
python
def reverse_name_server(self, query, limit=None, **kwargs): """Pass in a domain name or a name server.""" return self._results('reverse-name-server', '/v1/{0}/name-server-domains'.format(query), items_path=('primary_domains', ), limit=limit, **kwargs)
Pass in a domain name or a name server.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L158-L161
DomainTools/python_api
domaintools/api.py
API.reverse_whois
def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs): """List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ). """ return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited(query), exclude=delimited(exclude), scope=scope, mode=mode, **kwargs)
python
def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs): """List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ). """ return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited(query), exclude=delimited(exclude), scope=scope, mode=mode, **kwargs)
List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ).
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L163-L168
DomainTools/python_api
domaintools/api.py
API.whois_history
def whois_history(self, query, **kwargs): """Pass in a domain name.""" return self._results('whois-history', '/v1/{0}/whois/history'.format(query), items_path=('history', ), **kwargs)
python
def whois_history(self, query, **kwargs): """Pass in a domain name.""" return self._results('whois-history', '/v1/{0}/whois/history'.format(query), items_path=('history', ), **kwargs)
Pass in a domain name.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L174-L176
DomainTools/python_api
domaintools/api.py
API.phisheye
def phisheye(self, query, days_back=None, **kwargs): """Returns domain results for the specified term for today or the specified number of days_back. Terms must be setup for monitoring via the web interface: https://research.domaintools.com/phisheye. NOTE: Properties of a domain are only provided if we have been able to obtain them. Many domains will have incomplete data because that information isn't available in their Whois records, or they don't have DNS results for a name server or IP address. """ return self._results('phisheye', '/v1/phisheye', query=query, days_back=days_back, items_path=('domains', ), **kwargs)
python
def phisheye(self, query, days_back=None, **kwargs): """Returns domain results for the specified term for today or the specified number of days_back. Terms must be setup for monitoring via the web interface: https://research.domaintools.com/phisheye. NOTE: Properties of a domain are only provided if we have been able to obtain them. Many domains will have incomplete data because that information isn't available in their Whois records, or they don't have DNS results for a name server or IP address. """ return self._results('phisheye', '/v1/phisheye', query=query, days_back=days_back, items_path=('domains', ), **kwargs)
Returns domain results for the specified term for today or the specified number of days_back. Terms must be setup for monitoring via the web interface: https://research.domaintools.com/phisheye. NOTE: Properties of a domain are only provided if we have been able to obtain them. Many domains will have incomplete data because that information isn't available in their Whois records, or they don't have DNS results for a name server or IP address.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L178-L187
DomainTools/python_api
domaintools/api.py
API.phisheye_term_list
def phisheye_term_list(self, include_inactive=False, **kwargs): """Provides a list of terms that are set up for this account. This call is not charged against your API usage limit. NOTE: The terms must be configured in the PhishEye web interface: https://research.domaintools.com/phisheye. There is no API call to set up the terms. """ return self._results('phisheye_term_list', '/v1/phisheye/term-list', include_inactive=include_inactive, items_path=('terms', ), **kwargs)
python
def phisheye_term_list(self, include_inactive=False, **kwargs): """Provides a list of terms that are set up for this account. This call is not charged against your API usage limit. NOTE: The terms must be configured in the PhishEye web interface: https://research.domaintools.com/phisheye. There is no API call to set up the terms. """ return self._results('phisheye_term_list', '/v1/phisheye/term-list', include_inactive=include_inactive, items_path=('terms', ), **kwargs)
Provides a list of terms that are set up for this account. This call is not charged against your API usage limit. NOTE: The terms must be configured in the PhishEye web interface: https://research.domaintools.com/phisheye. There is no API call to set up the terms.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L189-L197
DomainTools/python_api
domaintools/api.py
API.iris
def iris(self, domain=None, ip=None, email=None, nameserver=None, registrar=None, registrant=None, registrant_org=None, **kwargs): """Performs a search for the provided search terms ANDed together, returning the pivot engine row data for the resulting domains. """ if ((not domain and not ip and not email and not nameserver and not registrar and not registrant and not registrant_org and not kwargs)): raise ValueError('At least one search term must be specified') return self._results('iris', '/v1/iris', domain=domain, ip=ip, email=email, nameserver=nameserver, registrar=registrar, registrant=registrant, registrant_org=registrant_org, items_path=('results', ), **kwargs)
python
def iris(self, domain=None, ip=None, email=None, nameserver=None, registrar=None, registrant=None, registrant_org=None, **kwargs): """Performs a search for the provided search terms ANDed together, returning the pivot engine row data for the resulting domains. """ if ((not domain and not ip and not email and not nameserver and not registrar and not registrant and not registrant_org and not kwargs)): raise ValueError('At least one search term must be specified') return self._results('iris', '/v1/iris', domain=domain, ip=ip, email=email, nameserver=nameserver, registrar=registrar, registrant=registrant, registrant_org=registrant_org, items_path=('results', ), **kwargs)
Performs a search for the provided search terms ANDed together, returning the pivot engine row data for the resulting domains.
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L199-L210
DomainTools/python_api
domaintools/api.py
API.risk
def risk(self, domain, **kwargs): """Returns back the risk score for a given domain""" return self._results('risk', '/v1/risk', items_path=('components', ), domain=domain, cls=Reputation, **kwargs)
python
def risk(self, domain, **kwargs): """Returns back the risk score for a given domain""" return self._results('risk', '/v1/risk', items_path=('components', ), domain=domain, cls=Reputation, **kwargs)
Returns back the risk score for a given domain
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L212-L215
DomainTools/python_api
domaintools/api.py
API.risk_evidence
def risk_evidence(self, domain, **kwargs): """Returns back the detailed risk evidence associated with a given domain""" return self._results('risk-evidence', '/v1/risk/evidence/', items_path=('components', ), domain=domain, **kwargs)
python
def risk_evidence(self, domain, **kwargs): """Returns back the detailed risk evidence associated with a given domain""" return self._results('risk-evidence', '/v1/risk/evidence/', items_path=('components', ), domain=domain, **kwargs)
Returns back the detailed risk evidence associated with a given domain
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L217-L220
DomainTools/python_api
domaintools/api.py
API.iris_enrich
def iris_enrich(self, *domains, **kwargs): """Returns back enriched data related to the specified domains using our Iris Enrich service each domain should be passed in as an un-named argument to the method: iris_enrich('domaintools.com', 'google.com') api.iris_enrich(*DOMAIN_LIST)['results_count'] Returns the number of results api.iris_enrich(*DOMAIN_LIST)['missing_domains'] Returns any domains that we were unable to retrieve enrichment data for api.iris_enrich(*DOMAIN_LIST)['limit_exceeded'] Returns True if you've exceeded your API usage for enrichment in api.iris_enrich(*DOMAIN_LIST): # Enables looping over all returned enriched domains for example: enrich_domains = ['google.com', 'amazon.com'] assert api.iris_enrich(*enrich_domains)['missing_domains'] == [] """ if not domains: raise ValueError('One or more domains to enrich must be provided') domains = ','.join(domains) data_updated_after = kwargs.get('data_updated_after', None) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_after.strftime('%Y-%M-%d') return self._results('iris-enrich', '/v1/iris-enrich/', domain=domains, data_updated_after=data_updated_after, items_path=('results', ), **kwargs)
python
def iris_enrich(self, *domains, **kwargs): """Returns back enriched data related to the specified domains using our Iris Enrich service each domain should be passed in as an un-named argument to the method: iris_enrich('domaintools.com', 'google.com') api.iris_enrich(*DOMAIN_LIST)['results_count'] Returns the number of results api.iris_enrich(*DOMAIN_LIST)['missing_domains'] Returns any domains that we were unable to retrieve enrichment data for api.iris_enrich(*DOMAIN_LIST)['limit_exceeded'] Returns True if you've exceeded your API usage for enrichment in api.iris_enrich(*DOMAIN_LIST): # Enables looping over all returned enriched domains for example: enrich_domains = ['google.com', 'amazon.com'] assert api.iris_enrich(*enrich_domains)['missing_domains'] == [] """ if not domains: raise ValueError('One or more domains to enrich must be provided') domains = ','.join(domains) data_updated_after = kwargs.get('data_updated_after', None) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_after.strftime('%Y-%M-%d') return self._results('iris-enrich', '/v1/iris-enrich/', domain=domains, data_updated_after=data_updated_after, items_path=('results', ), **kwargs)
Returns back enriched data related to the specified domains using our Iris Enrich service each domain should be passed in as an un-named argument to the method: iris_enrich('domaintools.com', 'google.com') api.iris_enrich(*DOMAIN_LIST)['results_count'] Returns the number of results api.iris_enrich(*DOMAIN_LIST)['missing_domains'] Returns any domains that we were unable to retrieve enrichment data for api.iris_enrich(*DOMAIN_LIST)['limit_exceeded'] Returns True if you've exceeded your API usage for enrichment in api.iris_enrich(*DOMAIN_LIST): # Enables looping over all returned enriched domains for example: enrich_domains = ['google.com', 'amazon.com'] assert api.iris_enrich(*enrich_domains)['missing_domains'] == []
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L222-L247
DomainTools/python_api
domaintools/api.py
API.iris_investigate
def iris_investigate(self, domains=None, data_updated_after=None, expiration_date=None, create_date=None, active=None, **kwargs): """Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: - ip: Search for domains having this IP. - email: Search for domains with this email in their data. - email_domain: Search for domains where the email address uses this domain. - nameserver_host: Search for domains with this nameserver. - nameserver_domain: Search for domains with a nameserver that has this domain. - nameserver_ip: Search for domains with a nameserver on this IP. - registrar: Search for domains with this registrar. - registrant: Search for domains with this registrant name. - registrant_org: Search for domains with this registrant organization. - mailserver_host: Search for domains with this mailserver. - mailserver_domain: Search for domains with a mailserver that has this domain. - mailserver_ip: Search for domains with a mailserver on this IP. - redirect_domain: Search for domains which redirect to this domain. - ssl_hash: Search for domains which have an SSL certificate with this hash. - ssl_subject: Search for domains which have an SSL certificate with this subject string. - ssl_email: Search for domains which have an SSL certificate with this email in it. - ssl_org: Search for domains which have an SSL certificate with this organization in it. - google_analytics: Search for domains which have this Google Analytics code. - adsense: Search for domains which have this AdSense code. - tld: Filter by TLD. Must be combined with another parameter. You can loop over results of your investigation as if it was a native Python list: for result in api.iris_investigate(ip='199.30.228.112'): # Enables looping over all related results api.iris_investigate(QUERY)['results_count'] Returns the number of results returned with this request api.iris_investigate(QUERY)['total_count'] Returns the number of results available within Iris api.iris_investigate(QUERY)['missing_domains'] Returns any domains that we were unable to find api.iris_investigate(QUERY)['limit_exceeded'] Returns True if you've exceeded your API usage api.iris_investigate(QUERY)['position'] Returns the position key that can be used to retrieve the next page: next_page = api.iris_investigate(QUERY, position=api.iris_investigate(QUERY)['position']) for enrichment in api.iris_enrich(i): # Enables looping over all returned enriched domains """ if not (kwargs or domains): raise ValueError('Need to define investigation using kwarg filters or domains') if type(domains) in (list, tuple): domains = ','.join(domains) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_after.strftime('%Y-%M-%d') if hasattr(expiration_date, 'strftime'): expiration_date = expiration_date.strftime('%Y-%M-%d') if hasattr(create_date, 'strftime'): create_date = create_date.strftime('%Y-%M-%d') if type(active) == bool: active = str(active).lower() return self._results('iris-investigate', '/v1/iris-investigate/', domain=domains, data_updated_after=data_updated_after, expiration_date=expiration_date, create_date=create_date, items_path=('results', ), **kwargs)
python
def iris_investigate(self, domains=None, data_updated_after=None, expiration_date=None, create_date=None, active=None, **kwargs): """Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: - ip: Search for domains having this IP. - email: Search for domains with this email in their data. - email_domain: Search for domains where the email address uses this domain. - nameserver_host: Search for domains with this nameserver. - nameserver_domain: Search for domains with a nameserver that has this domain. - nameserver_ip: Search for domains with a nameserver on this IP. - registrar: Search for domains with this registrar. - registrant: Search for domains with this registrant name. - registrant_org: Search for domains with this registrant organization. - mailserver_host: Search for domains with this mailserver. - mailserver_domain: Search for domains with a mailserver that has this domain. - mailserver_ip: Search for domains with a mailserver on this IP. - redirect_domain: Search for domains which redirect to this domain. - ssl_hash: Search for domains which have an SSL certificate with this hash. - ssl_subject: Search for domains which have an SSL certificate with this subject string. - ssl_email: Search for domains which have an SSL certificate with this email in it. - ssl_org: Search for domains which have an SSL certificate with this organization in it. - google_analytics: Search for domains which have this Google Analytics code. - adsense: Search for domains which have this AdSense code. - tld: Filter by TLD. Must be combined with another parameter. You can loop over results of your investigation as if it was a native Python list: for result in api.iris_investigate(ip='199.30.228.112'): # Enables looping over all related results api.iris_investigate(QUERY)['results_count'] Returns the number of results returned with this request api.iris_investigate(QUERY)['total_count'] Returns the number of results available within Iris api.iris_investigate(QUERY)['missing_domains'] Returns any domains that we were unable to find api.iris_investigate(QUERY)['limit_exceeded'] Returns True if you've exceeded your API usage api.iris_investigate(QUERY)['position'] Returns the position key that can be used to retrieve the next page: next_page = api.iris_investigate(QUERY, position=api.iris_investigate(QUERY)['position']) for enrichment in api.iris_enrich(i): # Enables looping over all returned enriched domains """ if not (kwargs or domains): raise ValueError('Need to define investigation using kwarg filters or domains') if type(domains) in (list, tuple): domains = ','.join(domains) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_after.strftime('%Y-%M-%d') if hasattr(expiration_date, 'strftime'): expiration_date = expiration_date.strftime('%Y-%M-%d') if hasattr(create_date, 'strftime'): create_date = create_date.strftime('%Y-%M-%d') if type(active) == bool: active = str(active).lower() return self._results('iris-investigate', '/v1/iris-investigate/', domain=domains, data_updated_after=data_updated_after, expiration_date=expiration_date, create_date=create_date, items_path=('results', ), **kwargs)
Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: - ip: Search for domains having this IP. - email: Search for domains with this email in their data. - email_domain: Search for domains where the email address uses this domain. - nameserver_host: Search for domains with this nameserver. - nameserver_domain: Search for domains with a nameserver that has this domain. - nameserver_ip: Search for domains with a nameserver on this IP. - registrar: Search for domains with this registrar. - registrant: Search for domains with this registrant name. - registrant_org: Search for domains with this registrant organization. - mailserver_host: Search for domains with this mailserver. - mailserver_domain: Search for domains with a mailserver that has this domain. - mailserver_ip: Search for domains with a mailserver on this IP. - redirect_domain: Search for domains which redirect to this domain. - ssl_hash: Search for domains which have an SSL certificate with this hash. - ssl_subject: Search for domains which have an SSL certificate with this subject string. - ssl_email: Search for domains which have an SSL certificate with this email in it. - ssl_org: Search for domains which have an SSL certificate with this organization in it. - google_analytics: Search for domains which have this Google Analytics code. - adsense: Search for domains which have this AdSense code. - tld: Filter by TLD. Must be combined with another parameter. You can loop over results of your investigation as if it was a native Python list: for result in api.iris_investigate(ip='199.30.228.112'): # Enables looping over all related results api.iris_investigate(QUERY)['results_count'] Returns the number of results returned with this request api.iris_investigate(QUERY)['total_count'] Returns the number of results available within Iris api.iris_investigate(QUERY)['missing_domains'] Returns any domains that we were unable to find api.iris_investigate(QUERY)['limit_exceeded'] Returns True if you've exceeded your API usage api.iris_investigate(QUERY)['position'] Returns the position key that can be used to retrieve the next page: next_page = api.iris_investigate(QUERY, position=api.iris_investigate(QUERY)['position']) for enrichment in api.iris_enrich(i): # Enables looping over all returned enriched domains
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L249-L305
AndrewRPorter/yahoo-historical
yahoo_historical/fetch.py
Fetcher.init
def init(self): """Returns a tuple pair of cookie and crumb used in the request""" url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker) r = requests.get(url) txt = r.content cookie = r.cookies['B'] pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}') for line in txt.splitlines(): m = pattern.match(line.decode("utf-8")) if m is not None: crumb = m.groupdict()['crumb'] crumb = crumb.replace(u'\\u002F', '/') return cookie, crumb
python
def init(self): """Returns a tuple pair of cookie and crumb used in the request""" url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker) r = requests.get(url) txt = r.content cookie = r.cookies['B'] pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}') for line in txt.splitlines(): m = pattern.match(line.decode("utf-8")) if m is not None: crumb = m.groupdict()['crumb'] crumb = crumb.replace(u'\\u002F', '/') return cookie, crumb
Returns a tuple pair of cookie and crumb used in the request
https://github.com/AndrewRPorter/yahoo-historical/blob/7a501af77fec6aa69551edb0485b665ea9bb2727/yahoo_historical/fetch.py#L26-L39
AndrewRPorter/yahoo-historical
yahoo_historical/fetch.py
Fetcher.getData
def getData(self, events): """Returns a list of historical data from Yahoo Finance""" if self.interval not in ["1d", "1wk", "1mo"]: raise ValueError("Incorrect interval: valid intervals are 1d, 1wk, 1mo") url = self.api_url % (self.ticker, self.start, self.end, self.interval, events, self.crumb) data = requests.get(url, cookies={'B':self.cookie}) content = StringIO(data.content.decode("utf-8")) return pd.read_csv(content, sep=',')
python
def getData(self, events): """Returns a list of historical data from Yahoo Finance""" if self.interval not in ["1d", "1wk", "1mo"]: raise ValueError("Incorrect interval: valid intervals are 1d, 1wk, 1mo") url = self.api_url % (self.ticker, self.start, self.end, self.interval, events, self.crumb) data = requests.get(url, cookies={'B':self.cookie}) content = StringIO(data.content.decode("utf-8")) return pd.read_csv(content, sep=',')
Returns a list of historical data from Yahoo Finance
https://github.com/AndrewRPorter/yahoo-historical/blob/7a501af77fec6aa69551edb0485b665ea9bb2727/yahoo_historical/fetch.py#L41-L50
ralphje/imagemounter
imagemounter/disk.py
Disk._get_mount_methods
def _get_mount_methods(self, disk_type): """Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount methods. """ if self.disk_mounter == 'auto': methods = [] def add_method_if_exists(method): if (method == 'avfs' and _util.command_exists('avfsd')) or \ _util.command_exists(method): methods.append(method) if self.read_write: add_method_if_exists('xmount') else: if disk_type == 'encase': add_method_if_exists('ewfmount') elif disk_type == 'vmdk': add_method_if_exists('vmware-mount') add_method_if_exists('affuse') elif disk_type == 'dd': add_method_if_exists('affuse') elif disk_type == 'compressed': add_method_if_exists('avfs') elif disk_type == 'qcow2': add_method_if_exists('qemu-nbd') elif disk_type == 'vdi': add_method_if_exists('qemu-nbd') add_method_if_exists('xmount') else: methods = [self.disk_mounter] return methods
python
def _get_mount_methods(self, disk_type): """Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount methods. """ if self.disk_mounter == 'auto': methods = [] def add_method_if_exists(method): if (method == 'avfs' and _util.command_exists('avfsd')) or \ _util.command_exists(method): methods.append(method) if self.read_write: add_method_if_exists('xmount') else: if disk_type == 'encase': add_method_if_exists('ewfmount') elif disk_type == 'vmdk': add_method_if_exists('vmware-mount') add_method_if_exists('affuse') elif disk_type == 'dd': add_method_if_exists('affuse') elif disk_type == 'compressed': add_method_if_exists('avfs') elif disk_type == 'qcow2': add_method_if_exists('qemu-nbd') elif disk_type == 'vdi': add_method_if_exists('qemu-nbd') add_method_if_exists('xmount') else: methods = [self.disk_mounter] return methods
Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount methods.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L89-L120
ralphje/imagemounter
imagemounter/disk.py
Disk._mount_avfs
def _mount_avfs(self): """Mounts the AVFS filesystem.""" self._paths['avfs'] = tempfile.mkdtemp(prefix='image_mounter_avfs_') # start by calling the mountavfs command to initialize avfs _util.check_call_(['avfsd', self._paths['avfs'], '-o', 'allow_other'], stdout=subprocess.PIPE) # no multifile support for avfs avfspath = self._paths['avfs'] + '/' + os.path.abspath(self.paths[0]) + '#' targetraw = os.path.join(self.mountpoint, 'avfs') os.symlink(avfspath, targetraw) logger.debug("Symlinked {} with {}".format(avfspath, targetraw)) raw_path = self.get_raw_path() logger.debug("Raw path to avfs is {}".format(raw_path)) if raw_path is None: raise MountpointEmptyError()
python
def _mount_avfs(self): """Mounts the AVFS filesystem.""" self._paths['avfs'] = tempfile.mkdtemp(prefix='image_mounter_avfs_') # start by calling the mountavfs command to initialize avfs _util.check_call_(['avfsd', self._paths['avfs'], '-o', 'allow_other'], stdout=subprocess.PIPE) # no multifile support for avfs avfspath = self._paths['avfs'] + '/' + os.path.abspath(self.paths[0]) + '#' targetraw = os.path.join(self.mountpoint, 'avfs') os.symlink(avfspath, targetraw) logger.debug("Symlinked {} with {}".format(avfspath, targetraw)) raw_path = self.get_raw_path() logger.debug("Raw path to avfs is {}".format(raw_path)) if raw_path is None: raise MountpointEmptyError()
Mounts the AVFS filesystem.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L122-L139
ralphje/imagemounter
imagemounter/disk.py
Disk.mount
def mount(self): """Mounts the base image on a temporary location using the mount method stored in :attr:`method`. If mounting was successful, :attr:`mountpoint` is set to the temporary mountpoint. If :attr:`read_write` is enabled, a temporary read-write cache is also created and stored in :attr:`rwpath`. :return: whether the mounting was successful :rtype: bool """ if self.parser.casename: self.mountpoint = tempfile.mkdtemp(prefix='image_mounter_', suffix='_' + self.parser.casename) else: self.mountpoint = tempfile.mkdtemp(prefix='image_mounter_') if self.read_write: self.rwpath = tempfile.mkstemp(prefix="image_mounter_rw_cache_")[1] disk_type = self.get_disk_type() methods = self._get_mount_methods(disk_type) cmds = [] for method in methods: if method == 'avfs': # avfs does not participate in the fallback stuff, unfortunately self._mount_avfs() self.disk_mounter = method self.was_mounted = True self.is_mounted = True return elif method == 'dummy': os.rmdir(self.mountpoint) self.mountpoint = "" logger.debug("Raw path to dummy is {}".format(self.get_raw_path())) self.disk_mounter = method self.was_mounted = True self.is_mounted = True return elif method == 'xmount': cmds.append(['xmount', ]) if self.read_write: cmds[-1].extend(['--cache', self.rwpath]) cmds[-1].extend(['--in', 'ewf' if disk_type == 'encase' else 'dd']) cmds[-1].extend(self.paths) # specify all paths, xmount needs this :( cmds[-1].append(self.mountpoint) elif method == 'affuse': cmds.extend([['affuse', '-o', 'allow_other', self.paths[0], self.mountpoint], ['affuse', self.paths[0], self.mountpoint]]) elif method == 'ewfmount': cmds.extend([['ewfmount', '-X', 'allow_other', self.paths[0], self.mountpoint], ['ewfmount', self.paths[0], self.mountpoint]]) elif method == 'vmware-mount': cmds.append(['vmware-mount', '-r', '-f', self.paths[0], self.mountpoint]) elif method == 'qemu-nbd': _util.check_output_(['modprobe', 'nbd', 'max_part=63']) # Load nbd driver try: self._paths['nbd'] = _util.get_free_nbd_device() # Get free nbd device except NoNetworkBlockAvailableError: logger.warning("No free network block device found.", exc_info=True) raise cmds.extend([['qemu-nbd', '--read-only', '-c', self._paths['nbd'], self.paths[0]]]) else: raise ArgumentError("Unknown mount method {0}".format(self.disk_mounter)) for cmd in cmds: # noinspection PyBroadException try: _util.check_call_(cmd, stdout=subprocess.PIPE) # mounting does not seem to be instant, add a timer here time.sleep(.1) except Exception: logger.warning('Could not mount {0}, trying other method'.format(self.paths[0]), exc_info=True) continue else: raw_path = self.get_raw_path() logger.debug("Raw path to disk is {}".format(raw_path)) self.disk_mounter = cmd[0] if raw_path is None: raise MountpointEmptyError() self.was_mounted = True self.is_mounted = True return logger.error('Unable to mount {0}'.format(self.paths[0])) os.rmdir(self.mountpoint) self.mountpoint = "" raise MountError()
python
def mount(self): """Mounts the base image on a temporary location using the mount method stored in :attr:`method`. If mounting was successful, :attr:`mountpoint` is set to the temporary mountpoint. If :attr:`read_write` is enabled, a temporary read-write cache is also created and stored in :attr:`rwpath`. :return: whether the mounting was successful :rtype: bool """ if self.parser.casename: self.mountpoint = tempfile.mkdtemp(prefix='image_mounter_', suffix='_' + self.parser.casename) else: self.mountpoint = tempfile.mkdtemp(prefix='image_mounter_') if self.read_write: self.rwpath = tempfile.mkstemp(prefix="image_mounter_rw_cache_")[1] disk_type = self.get_disk_type() methods = self._get_mount_methods(disk_type) cmds = [] for method in methods: if method == 'avfs': # avfs does not participate in the fallback stuff, unfortunately self._mount_avfs() self.disk_mounter = method self.was_mounted = True self.is_mounted = True return elif method == 'dummy': os.rmdir(self.mountpoint) self.mountpoint = "" logger.debug("Raw path to dummy is {}".format(self.get_raw_path())) self.disk_mounter = method self.was_mounted = True self.is_mounted = True return elif method == 'xmount': cmds.append(['xmount', ]) if self.read_write: cmds[-1].extend(['--cache', self.rwpath]) cmds[-1].extend(['--in', 'ewf' if disk_type == 'encase' else 'dd']) cmds[-1].extend(self.paths) # specify all paths, xmount needs this :( cmds[-1].append(self.mountpoint) elif method == 'affuse': cmds.extend([['affuse', '-o', 'allow_other', self.paths[0], self.mountpoint], ['affuse', self.paths[0], self.mountpoint]]) elif method == 'ewfmount': cmds.extend([['ewfmount', '-X', 'allow_other', self.paths[0], self.mountpoint], ['ewfmount', self.paths[0], self.mountpoint]]) elif method == 'vmware-mount': cmds.append(['vmware-mount', '-r', '-f', self.paths[0], self.mountpoint]) elif method == 'qemu-nbd': _util.check_output_(['modprobe', 'nbd', 'max_part=63']) # Load nbd driver try: self._paths['nbd'] = _util.get_free_nbd_device() # Get free nbd device except NoNetworkBlockAvailableError: logger.warning("No free network block device found.", exc_info=True) raise cmds.extend([['qemu-nbd', '--read-only', '-c', self._paths['nbd'], self.paths[0]]]) else: raise ArgumentError("Unknown mount method {0}".format(self.disk_mounter)) for cmd in cmds: # noinspection PyBroadException try: _util.check_call_(cmd, stdout=subprocess.PIPE) # mounting does not seem to be instant, add a timer here time.sleep(.1) except Exception: logger.warning('Could not mount {0}, trying other method'.format(self.paths[0]), exc_info=True) continue else: raw_path = self.get_raw_path() logger.debug("Raw path to disk is {}".format(raw_path)) self.disk_mounter = cmd[0] if raw_path is None: raise MountpointEmptyError() self.was_mounted = True self.is_mounted = True return logger.error('Unable to mount {0}'.format(self.paths[0])) os.rmdir(self.mountpoint) self.mountpoint = "" raise MountError()
Mounts the base image on a temporary location using the mount method stored in :attr:`method`. If mounting was successful, :attr:`mountpoint` is set to the temporary mountpoint. If :attr:`read_write` is enabled, a temporary read-write cache is also created and stored in :attr:`rwpath`. :return: whether the mounting was successful :rtype: bool
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L141-L234
ralphje/imagemounter
imagemounter/disk.py
Disk.get_raw_path
def get_raw_path(self): """Returns the raw path to the mounted disk image, i.e. the raw :file:`.dd`, :file:`.raw` or :file:`ewf1` file. :rtype: str """ if self.disk_mounter == 'dummy': return self.paths[0] else: if self.disk_mounter == 'avfs' and os.path.isdir(os.path.join(self.mountpoint, 'avfs')): logger.debug("AVFS mounted as a directory, will look in directory for (random) file.") # there is no support for disks inside disks, so this will fail to work for zips containing # E01 files or so. searchdirs = (os.path.join(self.mountpoint, 'avfs'), self.mountpoint) else: searchdirs = (self.mountpoint, ) raw_path = [] if self._paths.get('nbd'): raw_path.append(self._paths['nbd']) for searchdir in searchdirs: # avfs: apparently it is not a dir for pattern in ['*.dd', '*.iso', '*.raw', '*.dmg', 'ewf1', 'flat', 'avfs']: raw_path.extend(glob.glob(os.path.join(searchdir, pattern))) if not raw_path: logger.warning("No viable mount file found in {}.".format(searchdirs)) return None return raw_path[0]
python
def get_raw_path(self): """Returns the raw path to the mounted disk image, i.e. the raw :file:`.dd`, :file:`.raw` or :file:`ewf1` file. :rtype: str """ if self.disk_mounter == 'dummy': return self.paths[0] else: if self.disk_mounter == 'avfs' and os.path.isdir(os.path.join(self.mountpoint, 'avfs')): logger.debug("AVFS mounted as a directory, will look in directory for (random) file.") # there is no support for disks inside disks, so this will fail to work for zips containing # E01 files or so. searchdirs = (os.path.join(self.mountpoint, 'avfs'), self.mountpoint) else: searchdirs = (self.mountpoint, ) raw_path = [] if self._paths.get('nbd'): raw_path.append(self._paths['nbd']) for searchdir in searchdirs: # avfs: apparently it is not a dir for pattern in ['*.dd', '*.iso', '*.raw', '*.dmg', 'ewf1', 'flat', 'avfs']: raw_path.extend(glob.glob(os.path.join(searchdir, pattern))) if not raw_path: logger.warning("No viable mount file found in {}.".format(searchdirs)) return None return raw_path[0]
Returns the raw path to the mounted disk image, i.e. the raw :file:`.dd`, :file:`.raw` or :file:`ewf1` file. :rtype: str
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L236-L266
ralphje/imagemounter
imagemounter/disk.py
Disk.detect_volumes
def detect_volumes(self, single=None): """Generator that detects the volumes from the Disk, using one of two methods: * Single volume: the entire Disk is a single volume * Multiple volumes: the Disk is a volume system :param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`. If *single* is False, only :func:`init_multiple_volumes` is called. If *single* is None, :func:`init_multiple_volumes` is always called, being followed by :func:`init_single_volume` if no volumes were detected. """ # prevent adding the same volumes twice if self.volumes.has_detected: for v in self.volumes: yield v elif single: for v in self.volumes.detect_volumes(method='single'): yield v else: # if single == False or single == None, loop over all volumes amount = 0 try: for v in self.volumes.detect_volumes(): amount += 1 yield v except ImageMounterError: pass # ignore and continue to single mount # if single == None and no volumes were mounted, use single_volume if single is None and amount == 0: logger.info("Detecting as single volume instead") for v in self.volumes.detect_volumes(method='single', force=True): yield v
python
def detect_volumes(self, single=None): """Generator that detects the volumes from the Disk, using one of two methods: * Single volume: the entire Disk is a single volume * Multiple volumes: the Disk is a volume system :param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`. If *single* is False, only :func:`init_multiple_volumes` is called. If *single* is None, :func:`init_multiple_volumes` is always called, being followed by :func:`init_single_volume` if no volumes were detected. """ # prevent adding the same volumes twice if self.volumes.has_detected: for v in self.volumes: yield v elif single: for v in self.volumes.detect_volumes(method='single'): yield v else: # if single == False or single == None, loop over all volumes amount = 0 try: for v in self.volumes.detect_volumes(): amount += 1 yield v except ImageMounterError: pass # ignore and continue to single mount # if single == None and no volumes were mounted, use single_volume if single is None and amount == 0: logger.info("Detecting as single volume instead") for v in self.volumes.detect_volumes(method='single', force=True): yield v
Generator that detects the volumes from the Disk, using one of two methods: * Single volume: the entire Disk is a single volume * Multiple volumes: the Disk is a volume system :param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`. If *single* is False, only :func:`init_multiple_volumes` is called. If *single* is None, :func:`init_multiple_volumes` is always called, being followed by :func:`init_single_volume` if no volumes were detected.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L280-L314
ralphje/imagemounter
imagemounter/disk.py
Disk.init
def init(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True): """Calls several methods required to perform a full initialisation: :func:`mount`, and :func:`mount_volumes` and yields all detected volumes. :param bool|None single: indicates whether the disk should be mounted as a single disk, not as a single disk or whether it should try both (defaults to :const:`None`) :param list only_mount: If set, must be a list of volume indexes that are only mounted. :param list skip_mount: If set, must be a list of volume indexes tat should not be mounted. :param bool swallow_exceptions: If True, Exceptions are not raised but rather set on the instance. :rtype: generator """ self.mount() self.volumes.preload_volume_data() for v in self.init_volumes(single, only_mount=only_mount, skip_mount=skip_mount, swallow_exceptions=swallow_exceptions): yield v
python
def init(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True): """Calls several methods required to perform a full initialisation: :func:`mount`, and :func:`mount_volumes` and yields all detected volumes. :param bool|None single: indicates whether the disk should be mounted as a single disk, not as a single disk or whether it should try both (defaults to :const:`None`) :param list only_mount: If set, must be a list of volume indexes that are only mounted. :param list skip_mount: If set, must be a list of volume indexes tat should not be mounted. :param bool swallow_exceptions: If True, Exceptions are not raised but rather set on the instance. :rtype: generator """ self.mount() self.volumes.preload_volume_data() for v in self.init_volumes(single, only_mount=only_mount, skip_mount=skip_mount, swallow_exceptions=swallow_exceptions): yield v
Calls several methods required to perform a full initialisation: :func:`mount`, and :func:`mount_volumes` and yields all detected volumes. :param bool|None single: indicates whether the disk should be mounted as a single disk, not as a single disk or whether it should try both (defaults to :const:`None`) :param list only_mount: If set, must be a list of volume indexes that are only mounted. :param list skip_mount: If set, must be a list of volume indexes tat should not be mounted. :param bool swallow_exceptions: If True, Exceptions are not raised but rather set on the instance. :rtype: generator
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L316-L333
ralphje/imagemounter
imagemounter/disk.py
Disk.init_volumes
def init_volumes(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True): """Generator that detects and mounts all volumes in the disk. :param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`. If *single* is False, only :func:`init_multiple_volumes` is called. If *single* is None, :func:`init_multiple_volumes` is always called, being followed by :func:`init_single_volume` if no volumes were detected. :param list only_mount: If set, must be a list of volume indexes that are only mounted. :param list skip_mount: If set, must be a list of volume indexes tat should not be mounted. :param bool swallow_exceptions: If True, Exceptions are not raised but rather set on the instance. """ for volume in self.detect_volumes(single=single): for vol in volume.init(only_mount=only_mount, skip_mount=skip_mount, swallow_exceptions=swallow_exceptions): yield vol
python
def init_volumes(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True): """Generator that detects and mounts all volumes in the disk. :param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`. If *single* is False, only :func:`init_multiple_volumes` is called. If *single* is None, :func:`init_multiple_volumes` is always called, being followed by :func:`init_single_volume` if no volumes were detected. :param list only_mount: If set, must be a list of volume indexes that are only mounted. :param list skip_mount: If set, must be a list of volume indexes tat should not be mounted. :param bool swallow_exceptions: If True, Exceptions are not raised but rather set on the instance. """ for volume in self.detect_volumes(single=single): for vol in volume.init(only_mount=only_mount, skip_mount=skip_mount, swallow_exceptions=swallow_exceptions): yield vol
Generator that detects and mounts all volumes in the disk. :param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`. If *single* is False, only :func:`init_multiple_volumes` is called. If *single* is None, :func:`init_multiple_volumes` is always called, being followed by :func:`init_single_volume` if no volumes were detected. :param list only_mount: If set, must be a list of volume indexes that are only mounted. :param list skip_mount: If set, must be a list of volume indexes tat should not be mounted. :param bool swallow_exceptions: If True, Exceptions are not raised but rather set on the instance.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L335-L350
ralphje/imagemounter
imagemounter/disk.py
Disk.get_volumes
def get_volumes(self): """Gets a list of all volumes in this disk, including volumes that are contained in other volumes.""" volumes = [] for v in self.volumes: volumes.extend(v.get_volumes()) return volumes
python
def get_volumes(self): """Gets a list of all volumes in this disk, including volumes that are contained in other volumes.""" volumes = [] for v in self.volumes: volumes.extend(v.get_volumes()) return volumes
Gets a list of all volumes in this disk, including volumes that are contained in other volumes.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L352-L358
ralphje/imagemounter
imagemounter/disk.py
Disk.unmount
def unmount(self, remove_rw=False, allow_lazy=False): """Removes all ties of this disk to the filesystem, so the image can be unmounted successfully. :raises SubsystemError: when one of the underlying commands fails. Some are swallowed. :raises CleanupError: when actual cleanup fails. Some are swallowed. """ for m in list(sorted(self.volumes, key=lambda v: v.mountpoint or "", reverse=True)): try: m.unmount(allow_lazy=allow_lazy) except ImageMounterError: logger.warning("Error unmounting volume {0}".format(m.mountpoint)) if self._paths.get('nbd'): _util.clean_unmount(['qemu-nbd', '-d'], self._paths['nbd'], rmdir=False) if self.mountpoint: try: _util.clean_unmount(['fusermount', '-u'], self.mountpoint) except SubsystemError: if not allow_lazy: raise _util.clean_unmount(['fusermount', '-uz'], self.mountpoint) if self._paths.get('avfs'): try: _util.clean_unmount(['fusermount', '-u'], self._paths['avfs']) except SubsystemError: if not allow_lazy: raise _util.clean_unmount(['fusermount', '-uz'], self._paths['avfs']) if self.rw_active() and remove_rw: os.remove(self.rwpath) self.is_mounted = False
python
def unmount(self, remove_rw=False, allow_lazy=False): """Removes all ties of this disk to the filesystem, so the image can be unmounted successfully. :raises SubsystemError: when one of the underlying commands fails. Some are swallowed. :raises CleanupError: when actual cleanup fails. Some are swallowed. """ for m in list(sorted(self.volumes, key=lambda v: v.mountpoint or "", reverse=True)): try: m.unmount(allow_lazy=allow_lazy) except ImageMounterError: logger.warning("Error unmounting volume {0}".format(m.mountpoint)) if self._paths.get('nbd'): _util.clean_unmount(['qemu-nbd', '-d'], self._paths['nbd'], rmdir=False) if self.mountpoint: try: _util.clean_unmount(['fusermount', '-u'], self.mountpoint) except SubsystemError: if not allow_lazy: raise _util.clean_unmount(['fusermount', '-uz'], self.mountpoint) if self._paths.get('avfs'): try: _util.clean_unmount(['fusermount', '-u'], self._paths['avfs']) except SubsystemError: if not allow_lazy: raise _util.clean_unmount(['fusermount', '-uz'], self._paths['avfs']) if self.rw_active() and remove_rw: os.remove(self.rwpath) self.is_mounted = False
Removes all ties of this disk to the filesystem, so the image can be unmounted successfully. :raises SubsystemError: when one of the underlying commands fails. Some are swallowed. :raises CleanupError: when actual cleanup fails. Some are swallowed.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/disk.py#L365-L400
ralphje/imagemounter
imagemounter/cli/shell.py
ArgumentParsedShell._make_argparser
def _make_argparser(self): """Makes a new argument parser.""" self.argparser = ShellArgumentParser(prog='') subparsers = self.argparser.add_subparsers() for name in self.get_names(): if name.startswith('parser_'): parser = subparsers.add_parser(name[7:]) parser.set_defaults(func=getattr(self, 'arg_' + name[7:])) getattr(self, name)(parser) self.argparser_completer = None try: import argcomplete except ImportError: pass else: os.environ.setdefault("_ARGCOMPLETE_COMP_WORDBREAKS", " \t\"'") self.argparser_completer = argcomplete.CompletionFinder(self.argparser)
python
def _make_argparser(self): """Makes a new argument parser.""" self.argparser = ShellArgumentParser(prog='') subparsers = self.argparser.add_subparsers() for name in self.get_names(): if name.startswith('parser_'): parser = subparsers.add_parser(name[7:]) parser.set_defaults(func=getattr(self, 'arg_' + name[7:])) getattr(self, name)(parser) self.argparser_completer = None try: import argcomplete except ImportError: pass else: os.environ.setdefault("_ARGCOMPLETE_COMP_WORDBREAKS", " \t\"'") self.argparser_completer = argcomplete.CompletionFinder(self.argparser)
Makes a new argument parser.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L35-L54
ralphje/imagemounter
imagemounter/cli/shell.py
ArgumentParsedShell.complete
def complete(self, text, state): """Overridden to reset the argument parser after every completion (argcomplete fails :()""" result = cmd.Cmd.complete(self, text, state) if self.argparser_completer: self._make_argparser() # argparser screws up with internal states, this is the best way to fix it for now return result
python
def complete(self, text, state): """Overridden to reset the argument parser after every completion (argcomplete fails :()""" result = cmd.Cmd.complete(self, text, state) if self.argparser_completer: self._make_argparser() # argparser screws up with internal states, this is the best way to fix it for now return result
Overridden to reset the argument parser after every completion (argcomplete fails :()
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L60-L66
ralphje/imagemounter
imagemounter/cli/shell.py
ArgumentParsedShell.default
def default(self, line): """Overriding default to get access to any argparse commands we have specified.""" if any((line.startswith(x) for x in self.argparse_names())): try: args = self.argparser.parse_args(shlex.split(line)) except Exception: # intentionally catches also other errors in argparser pass else: args.func(args) else: cmd.Cmd.default(self, line)
python
def default(self, line): """Overriding default to get access to any argparse commands we have specified.""" if any((line.startswith(x) for x in self.argparse_names())): try: args = self.argparser.parse_args(shlex.split(line)) except Exception: # intentionally catches also other errors in argparser pass else: args.func(args) else: cmd.Cmd.default(self, line)
Overriding default to get access to any argparse commands we have specified.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L68-L79
ralphje/imagemounter
imagemounter/cli/shell.py
ArgumentParsedShell.completedefault
def completedefault(self, text, line, begidx, endidx): """Accessing the argcompleter if available.""" if self.argparser_completer and any((line.startswith(x) for x in self.argparse_names())): self.argparser_completer.rl_complete(line, 0) return [x[begidx:] for x in self.argparser_completer._rl_matches] else: return []
python
def completedefault(self, text, line, begidx, endidx): """Accessing the argcompleter if available.""" if self.argparser_completer and any((line.startswith(x) for x in self.argparse_names())): self.argparser_completer.rl_complete(line, 0) return [x[begidx:] for x in self.argparser_completer._rl_matches] else: return []
Accessing the argcompleter if available.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L81-L87
ralphje/imagemounter
imagemounter/cli/shell.py
ArgumentParsedShell.completenames
def completenames(self, text, *ignored): """Patched to also return argparse commands""" return sorted(cmd.Cmd.completenames(self, text, *ignored) + self.argparse_names(text))
python
def completenames(self, text, *ignored): """Patched to also return argparse commands""" return sorted(cmd.Cmd.completenames(self, text, *ignored) + self.argparse_names(text))
Patched to also return argparse commands
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L92-L94
ralphje/imagemounter
imagemounter/cli/shell.py
ArgumentParsedShell.do_help
def do_help(self, arg): """Patched to show help for arparse commands""" if not arg or arg not in self.argparse_names(): cmd.Cmd.do_help(self, arg) else: try: self.argparser.parse_args([arg, '--help']) except Exception: pass
python
def do_help(self, arg): """Patched to show help for arparse commands""" if not arg or arg not in self.argparse_names(): cmd.Cmd.do_help(self, arg) else: try: self.argparser.parse_args([arg, '--help']) except Exception: pass
Patched to show help for arparse commands
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L96-L104
ralphje/imagemounter
imagemounter/cli/shell.py
ArgumentParsedShell.print_topics
def print_topics(self, header, cmds, cmdlen, maxcol): """Patched to show all argparse commands as being documented""" if header == self.doc_header: cmds.extend(self.argparse_names()) cmd.Cmd.print_topics(self, header, sorted(cmds), cmdlen, maxcol)
python
def print_topics(self, header, cmds, cmdlen, maxcol): """Patched to show all argparse commands as being documented""" if header == self.doc_header: cmds.extend(self.argparse_names()) cmd.Cmd.print_topics(self, header, sorted(cmds), cmdlen, maxcol)
Patched to show all argparse commands as being documented
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L106-L110
ralphje/imagemounter
imagemounter/cli/shell.py
ImageMounterShell.preloop
def preloop(self): """if the parser is not already set, loads the parser.""" if not self.parser: self.stdout.write("Welcome to imagemounter {version}".format(version=__version__)) self.stdout.write("\n") self.parser = ImageParser() for p in self.args.paths: self.onecmd('disk "{}"'.format(p))
python
def preloop(self): """if the parser is not already set, loads the parser.""" if not self.parser: self.stdout.write("Welcome to imagemounter {version}".format(version=__version__)) self.stdout.write("\n") self.parser = ImageParser() for p in self.args.paths: self.onecmd('disk "{}"'.format(p))
if the parser is not already set, loads the parser.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L129-L137
ralphje/imagemounter
imagemounter/cli/shell.py
ImageMounterShell.onecmd
def onecmd(self, line): """Do not crash the entire program when a single command fails.""" try: return cmd.Cmd.onecmd(self, line) except Exception as e: print("Critical error.", e)
python
def onecmd(self, line): """Do not crash the entire program when a single command fails.""" try: return cmd.Cmd.onecmd(self, line) except Exception as e: print("Critical error.", e)
Do not crash the entire program when a single command fails.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L139-L144
ralphje/imagemounter
imagemounter/cli/shell.py
ImageMounterShell._get_all_indexes
def _get_all_indexes(self): """Returns all indexes available in the parser""" if self.parser: return [v.index for v in self.parser.get_volumes()] + [d.index for d in self.parser.disks] else: return None
python
def _get_all_indexes(self): """Returns all indexes available in the parser""" if self.parser: return [v.index for v in self.parser.get_volumes()] + [d.index for d in self.parser.disks] else: return None
Returns all indexes available in the parser
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L150-L155
ralphje/imagemounter
imagemounter/cli/shell.py
ImageMounterShell._get_by_index
def _get_by_index(self, index): """Returns a volume,disk tuple for the specified index""" volume_or_disk = self.parser.get_by_index(index) volume, disk = (volume_or_disk, None) if not isinstance(volume_or_disk, Disk) else (None, volume_or_disk) return volume, disk
python
def _get_by_index(self, index): """Returns a volume,disk tuple for the specified index""" volume_or_disk = self.parser.get_by_index(index) volume, disk = (volume_or_disk, None) if not isinstance(volume_or_disk, Disk) else (None, volume_or_disk) return volume, disk
Returns a volume,disk tuple for the specified index
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L157-L161
ralphje/imagemounter
imagemounter/cli/shell.py
ImageMounterShell.do_quit
def do_quit(self, arg): """Quits the program.""" if self.saved: self.save() else: self.parser.clean() return True
python
def do_quit(self, arg): """Quits the program.""" if self.saved: self.save() else: self.parser.clean() return True
Quits the program.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L418-L424
ralphje/imagemounter
imagemounter/unmounter.py
Unmounter.preview_unmount
def preview_unmount(self): """Returns a list of all commands that would be executed if the :func:`unmount` method would be called. Note: any system changes between calling this method and calling :func:`unmount` aren't listed by this command. """ commands = [] for mountpoint in self.find_bindmounts(): commands.append('umount {0}'.format(mountpoint)) for mountpoint in self.find_mounts(): commands.append('umount {0}'.format(mountpoint)) commands.append('rm -Rf {0}'.format(mountpoint)) for vgname, pvname in self.find_volume_groups(): commands.append('lvchange -a n {0}'.format(vgname)) commands.append('losetup -d {0}'.format(pvname)) for device in self.find_loopbacks(): commands.append('losetup -d {0}'.format(device)) for mountpoint in self.find_base_images(): commands.append('fusermount -u {0}'.format(mountpoint)) commands.append('rm -Rf {0}'.format(mountpoint)) for folder in self.find_clean_dirs(): cmd = 'rm -Rf {0}'.format(folder) if cmd not in commands: commands.append(cmd) return commands
python
def preview_unmount(self): """Returns a list of all commands that would be executed if the :func:`unmount` method would be called. Note: any system changes between calling this method and calling :func:`unmount` aren't listed by this command. """ commands = [] for mountpoint in self.find_bindmounts(): commands.append('umount {0}'.format(mountpoint)) for mountpoint in self.find_mounts(): commands.append('umount {0}'.format(mountpoint)) commands.append('rm -Rf {0}'.format(mountpoint)) for vgname, pvname in self.find_volume_groups(): commands.append('lvchange -a n {0}'.format(vgname)) commands.append('losetup -d {0}'.format(pvname)) for device in self.find_loopbacks(): commands.append('losetup -d {0}'.format(device)) for mountpoint in self.find_base_images(): commands.append('fusermount -u {0}'.format(mountpoint)) commands.append('rm -Rf {0}'.format(mountpoint)) for folder in self.find_clean_dirs(): cmd = 'rm -Rf {0}'.format(folder) if cmd not in commands: commands.append(cmd) return commands
Returns a list of all commands that would be executed if the :func:`unmount` method would be called. Note: any system changes between calling this method and calling :func:`unmount` aren't listed by this command.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/unmounter.py#L52-L76
ralphje/imagemounter
imagemounter/unmounter.py
Unmounter.unmount
def unmount(self): """Calls all unmount methods in the correct order.""" self.unmount_bindmounts() self.unmount_mounts() self.unmount_volume_groups() self.unmount_loopbacks() self.unmount_base_images() self.clean_dirs()
python
def unmount(self): """Calls all unmount methods in the correct order.""" self.unmount_bindmounts() self.unmount_mounts() self.unmount_volume_groups() self.unmount_loopbacks() self.unmount_base_images() self.clean_dirs()
Calls all unmount methods in the correct order.
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/unmounter.py#L78-L86