Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def handle_option(self, opt): self.options.append(opt) log.debug('options: %s', self.options)
[ "Store GPG agent-related options (e.g. for pinentry)." ]
Please provide a description of the function:def handle_get_passphrase(self, conn, _): p1 = self.client.device.ui.get_passphrase('Symmetric encryption:') p2 = self.client.device.ui.get_passphrase('Re-enter encryption:') if p1 == p2: result = b'D ' + util.assuan_serialize(p1....
[ "Allow simple GPG symmetric encryption (using a passphrase)." ]
Please provide a description of the function:def handle_getinfo(self, conn, args): result = None if args[0] == b'version': result = self.version elif args[0] == b's2k_count': # Use highest number of S2K iterations. # https://www.gnupg.org/documentatio...
[ "Handle some of the GETINFO messages." ]
Please provide a description of the function:def handle_scd(self, conn, args): reply = { (b'GETINFO', b'version'): self.version, }.get(args) if reply is None: raise AgentError(b'ERR 100696144 No such device <SCD>') keyring.sendline(conn, b'D ' + reply)
[ "No support for smart-card device protocol." ]
Please provide a description of the function:def get_identity(self, keygrip): keygrip_bytes = binascii.unhexlify(keygrip) pubkey_dict, user_ids = decode.load_by_keygrip( pubkey_bytes=self.pubkey_bytes, keygrip=keygrip_bytes) # We assume the first user ID is used to generate ...
[ "\n Returns device.interface.Identity that matches specified keygrip.\n\n In case of missing keygrip, KeyError will be raised.\n " ]
Please provide a description of the function:def pksign(self, conn): log.debug('signing %r digest (algo #%s)', self.digest, self.algo) identity = self.get_identity(keygrip=self.keygrip) r, s = self.client.sign(identity=identity, digest=binascii.unhexlify(...
[ "Sign a message digest using a private EC key." ]
Please provide a description of the function:def pkdecrypt(self, conn): for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']: keyring.sendline(conn, msg) line = keyring.recvline(conn) assert keyring.recvline(conn) == b'END' remote_pubkey = parse_ecdh(line) ...
[ "Handle decryption using ECDH." ]
Please provide a description of the function:def have_key(self, *keygrips): for keygrip in keygrips: try: self.get_identity(keygrip=keygrip) break except KeyError as e: log.warning('HAVEKEY(%s) failed: %s', keygrip, e) else...
[ "Check if any keygrip corresponds to a TREZOR-based key." ]
Please provide a description of the function:def set_hash(self, algo, digest): self.algo = algo self.digest = digest
[ "Set algorithm ID and hexadecimal digest for next operation." ]
Please provide a description of the function:def handle(self, conn): keyring.sendline(conn, b'OK') for line in keyring.iterlines(conn): parts = line.split(b' ') command = parts[0] args = tuple(parts[1:]) if command == b'BYE': retu...
[ "Handle connection from GPG binary using the ASSUAN protocol." ]
Please provide a description of the function:def _verify_support(identity, ecdh): protocol = identity.identity_dict['proto'] if protocol not in {'ssh'}: raise NotImplementedError( 'Unsupported protocol: {}'.format(protocol)) if ecdh: raise NotImplementedError('No support for...
[ "Make sure the device supports given configuration." ]
Please provide a description of the function:def pubkey(self, identity, ecdh=False): _verify_support(identity, ecdh) return trezor.Trezor.pubkey(self, identity=identity, ecdh=ecdh)
[ "Return public key." ]
Please provide a description of the function:def _verify_support(identity): if identity.curve_name not in {formats.CURVE_NIST256}: raise NotImplementedError( 'Unsupported elliptic curve: {}'.format(identity.curve_name))
[ "Make sure the device supports given configuration." ]
Please provide a description of the function:def connect(self): log.critical('NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!') log.critical('ONLY FOR DEBUGGING AND TESTING!!!') # The code below uses HARD-CODED secret key - and should be used ONLY # for GnuPG integration tests (e...
[ "Return \"dummy\" connection." ]
Please provide a description of the function:def pubkey(self, identity, ecdh=False): _verify_support(identity) data = self.vk.to_string() x, y = data[:32], data[32:] prefix = bytearray([2 + (bytearray(y)[0] & 1)]) return bytes(prefix) + x
[ "Return public key." ]
Please provide a description of the function:def sign(self, identity, blob): if identity.identity_dict['proto'] in {'ssh'}: digest = hashlib.sha256(blob).digest() else: digest = blob return self.sk.sign_digest_deterministic(digest=digest, ...
[ "Sign given blob and return the signature (as bytes)." ]
Please provide a description of the function:def ecdh(self, identity, pubkey): assert pubkey[:1] == b'\x04' peer = ecdsa.VerifyingKey.from_string( pubkey[1:], curve=ecdsa.curves.NIST256p, hashfunc=hashlib.sha256) shared = ecdsa.VerifyingKey.from_publi...
[ "Get shared session key using Elliptic Curve Diffie-Hellman." ]
Please provide a description of the function:def create_identity(user_id, curve_name): result = interface.Identity(identity_str='gpg://', curve_name=curve_name) result.identity_dict['host'] = user_id return result
[ "Create GPG identity for hardware device." ]
Please provide a description of the function:def pubkey(self, identity, ecdh=False): with self.device: pubkey = self.device.pubkey(ecdh=ecdh, identity=identity) return formats.decompress_pubkey( pubkey=pubkey, curve_name=identity.curve_name)
[ "Return public key as VerifyingKey object." ]
Please provide a description of the function:def sign(self, identity, digest): log.info('please confirm GPG signature on %s for "%s"...', self.device, identity.to_string()) if identity.curve_name == formats.CURVE_NIST256: digest = digest[:32] # sign the first 256 b...
[ "Sign the digest and return a serialized signature." ]
Please provide a description of the function:def ecdh(self, identity, pubkey): log.info('please confirm GPG decryption on %s for "%s"...', self.device, identity.to_string()) with self.device: return self.device.ecdh(pubkey=pubkey, identity=identity)
[ "Derive shared secret using ECDH from remote public key." ]
Please provide a description of the function:def connect(self): transport = self._defs.find_device() if not transport: raise interface.NotFoundError('{} not connected'.format(self)) log.debug('using transport: %s', transport) for _ in range(5): # Retry a few times ...
[ "Enumerate and connect to the first available interface." ]
Please provide a description of the function:def close(self): self.__class__.cached_state = self.conn.state super().close()
[ "Close connection." ]
Please provide a description of the function:def pubkey(self, identity, ecdh=False): curve_name = identity.get_curve_name(ecdh=ecdh) log.debug('"%s" getting public key (%s) from %s', identity.to_string(), curve_name, self) addr = identity.get_bip32_address(ecdh=ecdh) ...
[ "Return public key." ]
Please provide a description of the function:def sign(self, identity, blob): curve_name = identity.get_curve_name(ecdh=False) log.debug('"%s" signing %r (%s) on %s', identity.to_string(), blob, curve_name, self) try: result = self._defs.sign_identity( ...
[ "Sign given blob and return the signature (as bytes)." ]
Please provide a description of the function:def ecdh(self, identity, pubkey): curve_name = identity.get_curve_name(ecdh=True) log.debug('"%s" shared session key (%s) for %r from %s', identity.to_string(), curve_name, pubkey, self) try: result = self._defs....
[ "Get shared session key using Elliptic Curve Diffie-Hellman." ]
Please provide a description of the function:def string_to_identity(identity_str): m = _identity_regexp.match(identity_str) result = m.groupdict() log.debug('parsed identity: %s', result) return {k: v for k, v in result.items() if v}
[ "Parse string into Identity dictionary." ]
Please provide a description of the function:def identity_to_string(identity_dict): result = [] if identity_dict.get('proto'): result.append(identity_dict['proto'] + '://') if identity_dict.get('user'): result.append(identity_dict['user'] + '@') result.append(identity_dict['host']) ...
[ "Dump Identity dictionary into its string representation." ]
Please provide a description of the function:def items(self): return [(k, unidecode.unidecode(v)) for k, v in self.identity_dict.items()]
[ "Return a copy of identity_dict items." ]
Please provide a description of the function:def to_bytes(self): s = identity_to_string(self.identity_dict) return unidecode.unidecode(s).encode('ascii')
[ "Transliterate Unicode into ASCII." ]
Please provide a description of the function:def get_bip32_address(self, ecdh=False): index = struct.pack('<L', self.identity_dict.get('index', 0)) addr = index + self.to_bytes() log.debug('bip32 address string: %r', addr) digest = hashlib.sha256(addr).digest() s = io.By...
[ "Compute BIP32 derivation address according to SLIP-0013/0017." ]
Please provide a description of the function:def get_curve_name(self, ecdh=False): if ecdh: return formats.get_ecdh_curve_name(self.curve_name) else: return self.curve_name
[ "Return correct curve name for device operations." ]
Please provide a description of the function:def ssh_args(conn): I, = conn.identities identity = I.identity_dict pubkey_tempfile, = conn.public_keys_as_files() args = [] if 'port' in identity: args += ['-p', identity['port']] if 'user' in identity: args += ['-l', identity['...
[ "Create SSH command for connecting specified server." ]
Please provide a description of the function:def mosh_args(conn): I, = conn.identities identity = I.identity_dict args = [] if 'port' in identity: args += ['-p', identity['port']] if 'user' in identity: args += [identity['user']+'@'+identity['host']] else: args += [...
[ "Create SSH command for connecting specified server." ]
Please provide a description of the function:def create_agent_parser(device_type): epilog = ('See https://github.com/romanz/trezor-agent/blob/master/' 'doc/README-SSH.md for usage examples.') p = configargparse.ArgParser(default_config_files=['~/.ssh/agent.config'], ...
[ "Create an ArgumentParser for this tool." ]
Please provide a description of the function:def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT): ssh_version = subprocess.check_output(['ssh', '-V'], stderr=subprocess.STDOUT) log.debug('local SSH version: %r', ssh_version) environ = {'SSH_AUTH_SOCK': s...
[ "\n Start the ssh-agent server on a UNIX-domain socket.\n\n If no connection is made during the specified timeout,\n retry until the context is over.\n " ]
Please provide a description of the function:def run_server(conn, command, sock_path, debug, timeout): ret = 0 try: handler = protocol.Handler(conn=conn, debug=debug) with serve(handler=handler, sock_path=sock_path, timeout=timeout) as env: if command: ...
[ "Common code for run_agent and run_git below." ]
Please provide a description of the function:def handle_connection_error(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except device.interface.NotFoundError as e: log.error('Connection error (try unplugging and repluggi...
[ "Fail with non-zero exit code." ]
Please provide a description of the function:def parse_config(contents): for identity_str, curve_name in re.findall(r'\<(.*?)\|(.*?)\>', contents): yield device.interface.Identity(identity_str=identity_str, curve_name=curve_name)
[ "Parse config file into a list of Identity objects." ]
Please provide a description of the function:def import_public_keys(contents): for line in io.StringIO(contents): # Verify this line represents valid SSH public key formats.import_public_key(line) yield line
[ "Load (previously exported) SSH public keys from a file's contents." ]
Please provide a description of the function:def main(device_type): args = create_agent_parser(device_type=device_type).parse_args() util.setup_logging(verbosity=args.verbose, filename=args.log_file) public_keys = None filename = None if args.identity.startswith('/'): filename = args.i...
[ "Run ssh-agent using given hardware client factory." ]
Please provide a description of the function:def public_keys(self): if not self.public_keys_cache: conn = self.conn_factory() self.public_keys_cache = conn.export_public_keys(self.identities) return self.public_keys_cache
[ "Return a list of SSH public keys (in textual format)." ]
Please provide a description of the function:def parse_public_keys(self): public_keys = [formats.import_public_key(pk) for pk in self.public_keys()] for pk, identity in zip(public_keys, self.identities): pk['identity'] = identity return public_keys
[ "Parse SSH public keys into dictionaries." ]
Please provide a description of the function:def public_keys_as_files(self): if not self.public_keys_tempfiles: for pk in self.public_keys(): f = tempfile.NamedTemporaryFile(prefix='trezor-ssh-pubkey-', mode='w') f.write(pk) f.flush() ...
[ "Store public keys as temporary SSH identity files." ]
Please provide a description of the function:def sign(self, blob, identity): conn = self.conn_factory() return conn.sign_ssh_challenge(blob=blob, identity=identity)
[ "Sign a given blob using the specified identity on the device." ]
Please provide a description of the function:def packet(tag, blob): assert len(blob) < 2**32 if len(blob) < 2**8: length_type = 0 elif len(blob) < 2**16: length_type = 1 else: length_type = 2 fmt = ['>B', '>H', '>L'][length_type] leading_byte = 0x80 | (tag << 2) | ...
[ "Create small GPG packet." ]
Please provide a description of the function:def subpacket(subpacket_type, fmt, *values): blob = struct.pack(fmt, *values) if values else fmt return struct.pack('>B', subpacket_type) + blob
[ "Create GPG subpacket." ]
Please provide a description of the function:def subpacket_prefix_len(item): n = len(item) if n >= 8384: prefix = b'\xFF' + struct.pack('>L', n) elif n >= 192: n = n - 192 prefix = struct.pack('BB', (n // 256) + 192, n % 256) else: prefix = struct.pack('B', n) re...
[ "Prefix subpacket length according to RFC 4880 section-5.2.3.1." ]
Please provide a description of the function:def subpackets(*items): prefixed = [subpacket_prefix_len(item) for item in items] return util.prefix_len('>H', b''.join(prefixed))
[ "Serialize several GPG subpackets." ]
Please provide a description of the function:def mpi(value): bits = value.bit_length() data_size = (bits + 7) // 8 data_bytes = bytearray(data_size) for i in range(data_size): data_bytes[i] = value & 0xFF value = value >> 8 data_bytes.reverse() return struct.pack('>H', bits...
[ "Serialize multipresicion integer using GPG format." ]
Please provide a description of the function:def keygrip_nist256(vk): curve = vk.curve.curve gen = vk.curve.generator g = (4 << 512) | (gen.x() << 256) | gen.y() point = vk.pubkey.point q = (4 << 512) | (point.x() << 256) | point.y() return _compute_keygrip([ ['p', util.num2bytes(c...
[ "Compute keygrip for NIST256 curve public keys." ]
Please provide a description of the function:def keygrip_ed25519(vk): # pylint: disable=line-too-long return _compute_keygrip([ ['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8 ['a', b'\x01'], ['b', util.num2bytes(0x2DFC93...
[ "Compute keygrip for Ed25519 public keys." ]
Please provide a description of the function:def keygrip_curve25519(vk): # pylint: disable=line-too-long return _compute_keygrip([ ['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8 ['a', b'\x01\xDB\x41'], ['b', b'\x01'], ...
[ "Compute keygrip for Curve25519 public keys." ]
Please provide a description of the function:def get_curve_name_by_oid(oid): for curve_name, info in SUPPORTED_CURVES.items(): if info['oid'] == oid: return curve_name raise KeyError('Unknown OID: {!r}'.format(oid))
[ "Return curve name matching specified OID, or raise KeyError." ]
Please provide a description of the function:def armor(blob, type_str): head = '-----BEGIN PGP {}-----\nVersion: GnuPG v2\n\n'.format(type_str) body = base64.b64encode(blob).decode('ascii') checksum = base64.b64encode(util.crc24(blob)).decode('ascii') tail = '-----END PGP {}-----\n'.format(type_str...
[ "See https://tools.ietf.org/html/rfc4880#section-6 for details." ]
Please provide a description of the function:def make_signature(signer_func, data_to_sign, public_algo, hashed_subpackets, unhashed_subpackets, sig_type=0): # pylint: disable=too-many-arguments header = struct.pack('>BBBB', 4, # version ...
[ "Create new GPG signature." ]
Please provide a description of the function:def data(self): header = struct.pack('>BLB', 4, # version self.created, # creation self.algo_id) # public key algorithm ID oid = util.prefix_len('>B'...
[ "Data for packet creation." ]
Please provide a description of the function:def create_primary(user_id, pubkey, signer_func, secret_bytes=b''): pubkey_packet = protocol.packet(tag=(5 if secret_bytes else 6), blob=(pubkey.data() + secret_bytes)) user_id_bytes = user_id.encode('utf-8') user_id_packe...
[ "Export new primary GPG public key, ready for \"gpg2 --import\"." ]
Please provide a description of the function:def create_subkey(primary_bytes, subkey, signer_func, secret_bytes=b''): subkey_packet = protocol.packet(tag=(7 if secret_bytes else 14), blob=(subkey.data() + secret_bytes)) packets = list(decode.parse_packets(io.BytesIO(prim...
[ "Export new subkey to GPG primary key." ]
Please provide a description of the function:def export_public_key(device_type, args): log.warning('NOTE: in order to re-generate the exact same GPG key later, ' 'run this command with "--time=%d" commandline flag (to set ' 'the timestamp of the GPG key manually).', args.time) ...
[ "Generate a new pubkey for a new/existing GPG identity." ]
Please provide a description of the function:def verify_gpg_version(): existing_gpg = keyring.gpg_version().decode('ascii') required_gpg = '>=2.1.11' msg = 'Existing GnuPG has version "{}" ({} required)'.format(existing_gpg, required_gpg)...
[ "Make sure that the installed GnuPG is not too old." ]
Please provide a description of the function:def check_output(args): log.debug('run: %s', args) out = subprocess.check_output(args=args).decode('utf-8') log.debug('out: %r', out) return out
[ "Runs command and returns the output as string." ]
Please provide a description of the function:def check_call(args, stdin=None, env=None): log.debug('run: %s%s', args, ' {}'.format(env) if env else '') subprocess.check_call(args=args, stdin=stdin, env=env)
[ "Runs command and verifies its success." ]
Please provide a description of the function:def write_file(path, data): with open(path, 'w') as f: log.debug('setting %s contents:\n%s', path, data) f.write(data) return f
[ "Writes data to specified path." ]
Please provide a description of the function:def run_init(device_type, args): util.setup_logging(verbosity=args.verbose) log.warning('This GPG tool is still in EXPERIMENTAL mode, ' 'so please note that the API and features may ' 'change without backwards compatibility!') ...
[ "Initialize hardware-based GnuPG identity.", "#!/bin/sh\nexport PATH={0}\n{1} \\\n-vv \\\n--pin-entry-binary={pin_entry_binary} \\\n--passphrase-entry-binary={passphrase_entry_binary} \\\n--cache-expiry-seconds={cache_expiry_seconds} \\\n$*\n", "# Hardware-based GPG configuration\nagent-program {0}\npersonal-di...
Please provide a description of the function:def run_unlock(device_type, args): util.setup_logging(verbosity=args.verbose) with device_type() as d: log.info('unlocked %s device', d)
[ "Unlock hardware device (for future interaction)." ]
Please provide a description of the function:def run_agent(device_type): p = argparse.ArgumentParser() p.add_argument('--homedir', default=os.environ.get('GNUPGHOME')) p.add_argument('-v', '--verbose', default=0, action='count') p.add_argument('--server', default=False, action='store_true', ...
[ "Run a simple GPG-agent server." ]
Please provide a description of the function:def main(device_type): epilog = ('See https://github.com/romanz/trezor-agent/blob/master/' 'doc/README-GPG.md for usage examples.') parser = argparse.ArgumentParser(epilog=epilog) agent_package = device_type.package_name() resources_map = ...
[ "Parse command-line arguments." ]
Please provide a description of the function:def find_device(): try: return get_transport(os.environ.get("TREZOR_PATH")) except Exception as e: # pylint: disable=broad-except log.debug("Failed to find a Trezor device: %s", e)
[ "Selects a transport based on `TREZOR_PATH` environment variable.\n\n If unset, picks first connected device.\n " ]
Please provide a description of the function:def _convert_public_key(ecdsa_curve_name, result): if ecdsa_curve_name == 'nist256p1': if (result[64] & 1) != 0: result = bytearray([0x03]) + result[1:33] else: result = bytearray([0x02]) + result[1:33] else: resul...
[ "Convert Ledger reply into PublicKey object." ]
Please provide a description of the function:def connect(self): try: return comm.getDongle() except comm.CommException as e: raise interface.NotFoundError( '{} not connected: "{}"'.format(self, e))
[ "Enumerate and connect to the first USB HID interface." ]
Please provide a description of the function:def pubkey(self, identity, ecdh=False): curve_name = identity.get_curve_name(ecdh) path = _expand_path(identity.get_bip32_address(ecdh)) if curve_name == 'nist256p1': p2 = '01' else: p2 = '02' apdu = '8...
[ "Get PublicKey object for specified BIP32 address and elliptic curve." ]
Please provide a description of the function:def sign(self, identity, blob): path = _expand_path(identity.get_bip32_address(ecdh=False)) if identity.identity_dict['proto'] == 'ssh': ins = '04' p1 = '00' else: ins = '08' p1 = '00' i...
[ "Sign given blob and return the signature (as bytes)." ]
Please provide a description of the function:def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) try: from urllib.request import urlopen excep...
[ "Download distribute from a specified location and return its filename\n\n `version` should be a valid distribute version number that is available\n as an egg for download under the `download_base` URL (which should end\n with a '/'). `to_dir` is the directory where the egg will be downloaded.\n `delay`...
Please provide a description of the function:def tokenize(stream, separator): for value in stream: for token in value.split(separator): if token: yield token.strip()
[ "\n Tokenize and yield query parameter values.\n\n :param stream: Input value\n :param separator: Character to use to separate the tokens.\n :return:\n " ]
Please provide a description of the function:def build_query(self, **filters): applicable_filters = [] applicable_exclusions = [] for param, value in filters.items(): excluding_term = False param_parts = param.split("__") base_param = param_parts[0]...
[ "\n Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields\n that have been \"registered\" in `view.fields`.\n\n Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any\n querystring parameters that are not re...
Please provide a description of the function:def build_query(self, **filters): field_facets = {} date_facets = {} query_facets = {} facet_serializer_cls = self.view.get_facet_serializer_class() if self.view.lookup_sep == ":": raise AttributeError("The %(cls)...
[ "\n Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,\n `date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.\n\n :param view: API View\n :param dict[str, list[str]] filters: is an expanded QueryDict or a mapping\n ...
Please provide a description of the function:def parse_field_options(self, *options): defaults = {} for option in options: if isinstance(option, six.text_type): tokens = [token.strip() for token in option.split(self.view.lookup_sep)] for token in tok...
[ "\n Parse the field options query string and return it as a dictionary.\n " ]
Please provide a description of the function:def build_query(self, **filters): applicable_filters = None filters = dict((k, filters[k]) for k in chain(self.D.UNITS.keys(), [constants.DRF_HAYSTACK_SPATIAL_QUERY_PARAM]) if k in filters) ...
[ "\n Build queries for geo spatial filtering.\n\n Expected query parameters are:\n - a `unit=value` parameter where the unit is a valid UNIT in the\n `django.contrib.gis.measure.Distance` class.\n - `from` which must be a comma separated latitude and longitude.\n\n Exa...
Please provide a description of the function:def merge_dict(a, b): if not isinstance(b, dict): return b result = deepcopy(a) for key, val in six.iteritems(b): if key in result and isinstance(result[key], dict): result[key] = merge_dict(result[key], val) elif key in...
[ "\n Recursively merges and returns dict a with dict b.\n Any list values will be combined and returned sorted.\n\n :param a: dictionary object\n :param b: dictionary object\n :return: merged dictionary object\n " ]
Please provide a description of the function:def get_queryset(self, index_models=[]): if self.queryset is not None and isinstance(self.queryset, self.object_class): queryset = self.queryset.all() else: queryset = self.object_class()._clone() if len(index_mode...
[ "\n Get the list of items for this view.\n Returns ``self.queryset`` if defined and is a ``self.object_class``\n instance.\n\n @:param index_models: override `self.index_models`\n " ]
Please provide a description of the function:def get_object(self): queryset = self.get_queryset() if "model" in self.request.query_params: try: app_label, model = map(six.text_type.lower, self.request.query_params["model"].split(".", 1)) ctype = Conte...
[ "\n Fetch a single document from the data store according to whatever\n unique identifier is available for that document in the\n SearchIndex.\n\n In cases where the view has multiple ``index_models``, add a ``model`` query\n parameter containing a single `app_label.model` name to...
Please provide a description of the function:def more_like_this(self, request, pk=None): obj = self.get_object().object queryset = self.filter_queryset(self.get_queryset()).more_like_this(obj) page = self.paginate_queryset(queryset) if page is not None: serializer =...
[ "\n Sets up a detail route for ``more-like-this`` results.\n Note that you'll need backend support in order to take advantage of this.\n\n This will add ie. ^search/{pk}/more-like-this/$ to your existing ^search pattern.\n " ]
Please provide a description of the function:def facets(self, request): queryset = self.filter_facet_queryset(self.get_queryset()) for facet in request.query_params.getlist(self.facet_query_params_text): if ":" not in facet: continue field, value = fac...
[ "\n Sets up a list route for ``faceted`` results.\n This will add ie ^search/facets/$ to your existing ^search pattern.\n " ]
Please provide a description of the function:def filter_facet_queryset(self, queryset): for backend in list(self.facet_filter_backends): queryset = backend().filter_queryset(self.request, queryset, self) if self.load_all: queryset = queryset.load_all() return q...
[ "\n Given a search queryset, filter it with whichever facet filter backends\n in use.\n " ]
Please provide a description of the function:def get_facet_serializer(self, *args, **kwargs): assert "objects" in kwargs, "`objects` is a required argument to `get_facet_serializer()`" facet_serializer_class = self.get_facet_serializer_class() kwargs["context"] = self.get_serializer_co...
[ "\n Return the facet serializer instance that should be used for\n serializing faceted output.\n " ]
Please provide a description of the function:def get_facet_serializer_class(self): if self.facet_serializer_class is None: raise AttributeError( "%(cls)s should either include a `facet_serializer_class` attribute, " "or override %(cls)s.get_facet_serializer_c...
[ "\n Return the class to use for serializing facets.\n Defaults to using ``self.facet_serializer_class``.\n " ]
Please provide a description of the function:def get_facet_objects_serializer(self, *args, **kwargs): facet_objects_serializer_class = self.get_facet_objects_serializer_class() kwargs["context"] = self.get_serializer_context() return facet_objects_serializer_class(*args, **kwargs)
[ "\n Return the serializer instance which should be used for\n serializing faceted objects.\n " ]
Please provide a description of the function:def bind(self, field_name, parent): # In order to enforce a consistent style, we error if a redundant # 'source' argument has been used. For example: # my_field = serializer.CharField(source='my_field') assert self.source != field_na...
[ "\n Initializes the field name and parent for the field instance.\n Called when a field is added to the parent serializer instance.\n Taken from DRF and modified to support drf_haystack multiple index\n functionality.\n " ]
Please provide a description of the function:def _get_default_field_kwargs(model, field): kwargs = {} try: field_name = field.model_attr or field.index_fieldname model_field = model._meta.get_field(field_name) kwargs.update(get_field_kwargs(field_name, model_...
[ "\n Get the required attributes from the model field in order\n to instantiate a REST Framework serializer field.\n " ]
Please provide a description of the function:def _get_index_class_name(self, index_cls): cls_name = index_cls.__name__ aliases = self.Meta.index_aliases return aliases.get(cls_name, cls_name.split('.')[-1])
[ "\n Converts in index model class to a name suitable for use as a field name prefix. A user\n may optionally specify custom aliases via an 'index_aliases' attribute on the Meta class\n " ]
Please provide a description of the function:def get_fields(self): fields = self.Meta.fields exclude = self.Meta.exclude ignore_fields = self.Meta.ignore_fields indices = self.Meta.index_classes declared_fields = copy.deepcopy(self._declared_fields) prefix_fiel...
[ "\n Get the required fields for serializing the result.\n " ]
Please provide a description of the function:def to_representation(self, instance): if self.Meta.serializers: ret = self.multi_serializer_representation(instance) else: ret = super(HaystackSerializer, self).to_representation(instance) prefix_field_names = len...
[ "\n If we have a serializer mapping, use that. Otherwise, use standard serializer behavior\n Since we might be dealing with multiple indexes, some fields might\n not be valid for all results. Do not render the fields which don't belong\n to the search result.\n " ]
Please provide a description of the function:def get_paginate_by_param(self): if hasattr(self.root, "paginate_by_param") and self.root.paginate_by_param: return self.root.paginate_by_param pagination_class = self.context["view"].pagination_class if not pagination_class: ...
[ "\n Returns the ``paginate_by_param`` for the (root) view paginator class.\n This is needed in order to remove the query parameter from faceted\n narrow urls.\n\n If using a custom pagination class, this class attribute needs to\n be set manually.\n " ]
Please provide a description of the function:def get_text(self, instance): instance = instance[0] if isinstance(instance, (six.text_type, six.string_types)): return serializers.CharField(read_only=True).to_representation(instance) elif isinstance(instance, datetime): ...
[ "\n Haystack facets are returned as a two-tuple (value, count).\n The text field should contain the faceted value.\n " ]
Please provide a description of the function:def get_count(self, instance): instance = instance[1] return serializers.IntegerField(read_only=True).to_representation(instance)
[ "\n Haystack facets are returned as a two-tuple (value, count).\n The count field should contain the faceted count.\n " ]
Please provide a description of the function:def get_narrow_url(self, instance): text = instance[0] request = self.context["request"] query_params = request.GET.copy() # Never keep the page query parameter in narrowing urls. # It will raise a NotFound exception when try...
[ "\n Return a link suitable for narrowing on the current item.\n " ]
Please provide a description of the function:def to_representation(self, field, instance): self.parent_field = field return super(FacetFieldSerializer, self).to_representation(instance)
[ "\n Set the ``parent_field`` property equal to the current field on the serializer class,\n so that each field can query it to see what kind of attribute they are processing.\n " ]
Please provide a description of the function:def get_fields(self): field_mapping = OrderedDict() for field, data in self.instance.items(): field_mapping.update( {field: self.facet_dict_field_class( child=self.facet_list_field_class(child=self.face...
[ "\n This returns a dictionary containing the top most fields,\n ``dates``, ``fields`` and ``queries``.\n " ]
Please provide a description of the function:def get_objects(self, instance): view = self.context["view"] queryset = self.context["objects"] page = view.paginate_queryset(queryset) if page is not None: serializer = view.get_facet_objects_serializer(page, many=True) ...
[ "\n Return a list of objects matching the faceted result.\n " ]