You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

indexclient

Package Overview
Dependencies
Maintainers
2
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

indexclient - pypi Package Compare versions

Comparing version
1.5.8
to
2.1.0
+1
-1
indexclient.egg-info/PKG-INFO
Metadata-Version: 1.0
Name: indexclient
Version: 1.5.8
Version: 2.1.0
Summary: UNKNOWN

@@ -5,0 +5,0 @@ Home-page: UNKNOWN

@@ -1,6 +0,1 @@

LICENSE
MANIFEST.in
NOTICE
Pipfile
Pipfile.lock
README.md

@@ -7,0 +2,0 @@ setup.py

@@ -1,14 +0,19 @@

try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
import copy
import json
import warnings
import requests
from indexclient.errors import BaseIndexError
MAX_RETRIES = 10
UPDATABLE_ATTRS = [
'file_name', 'urls', 'version',
'metadata', 'acl', 'urls_metadata'
"file_name",
"urls",
"version",
"metadata",
"acl",
"authz",
"urls_metadata",
]

@@ -26,3 +31,3 @@

resp.reason = json["error"]
except KeyError:
except (json.decoder.JSONDecodeError, KeyError):
pass

@@ -33,4 +38,26 @@ finally:

def timeout_wrapper(func):
def timeout(*args, **kwargs):
kwargs.setdefault("timeout", 60)
return func(*args, **kwargs)
return timeout
def retry_and_timeout_wrapper(func):
def retry_logic_with_timeout(*args, **kwargs):
kwargs.setdefault("timeout", 60)
retries = 0
while retries < MAX_RETRIES:
try:
return func(*args, **kwargs)
except requests.exceptions.ReadTimeout:
retries += 1
if retries == MAX_RETRIES:
raise
return retry_logic_with_timeout
class IndexClient(object):
def __init__(self, baseurl, version="v0", auth=None):

@@ -42,7 +69,8 @@ self.auth = auth

def url_for(self, *path):
return urljoin(self.url, "/".join(path))
subpath = "/".join(path).lstrip("/")
return "{}/{}".format(self.url.rstrip("/"), subpath)
def check_status(self):
"""Check that the API we are trying to communicate with is online"""
resp = requests.get(self.url + '/index')
resp = requests.get(self.url + "/index")
handle_error(resp)

@@ -65,3 +93,3 @@

if no_dist:
response = self._get(did, params={'no_dist': ''})
response = self._get(did, params={"no_dist": ""})
else:

@@ -108,3 +136,3 @@ response = self._get(did)

headers = {'content-type': 'application/json'}
headers = {"content-type": "application/json"}
try:

@@ -118,6 +146,3 @@ response = self._post("bulk/documents", json=dids, headers=headers)

return [
Document(self, doc['did'], json=doc)
for doc in response.json()
]
return [Document(self, doc["did"], json=doc) for doc in response.json()]

@@ -133,16 +158,16 @@ def get_with_params(self, params=None):

params_copy = copy.deepcopy(params) or {}
if 'hashes' in params_copy:
params_copy['hash'] = params_copy.pop('hashes')
if "hashes" in params_copy:
params_copy["hash"] = params_copy.pop("hashes")
reformatted_params = dict()
for param in ['hash', 'metadata']:
for param in ["hash", "metadata"]:
if param in params_copy:
reformatted_params[param] = []
for k, v in params_copy[param].items():
reformatted_params[param].append(str(k) + ':' + str(v))
reformatted_params[param].append(str(k) + ":" + str(v))
del params_copy[param]
reformatted_params.update(params_copy)
reformatted_params['limit'] = 1
reformatted_params["limit"] = 1
try:
response = self._get('index', params=reformatted_params)
response = self._get("index", params=reformatted_params)
except requests.HTTPError as e:

@@ -153,6 +178,6 @@ if e.response.status_code == 404:

raise e
if not response.json()['records']:
if not response.json()["records"]:
return None
json = response.json()['records'][0]
did = json['did']
json = response.json()["records"][0]
did = json["did"]
return Document(self, did, json=json)

@@ -164,3 +189,10 @@

def list_with_params(self, limit=float("inf"), start=None, page_size=100, params=None, negate_params=None):
def list_with_params(
self,
limit=float("inf"),
start=None,
page_size=100,
params=None,
negate_params=None,
):
"""

@@ -175,12 +207,12 @@ Return a generator of document object corresponding to the supplied parameters, such

params_copy = copy.deepcopy(params) or {}
if 'hashes' in params_copy:
params_copy['hash'] = params_copy.pop('hashes')
if 'urls_metadata' in params_copy:
params_copy['urls_metadata'] = json.dumps(params_copy.pop('urls_metadata'))
if "hashes" in params_copy:
params_copy["hash"] = params_copy.pop("hashes")
if "urls_metadata" in params_copy:
params_copy["urls_metadata"] = json.dumps(params_copy.pop("urls_metadata"))
reformatted_params = dict()
for param in ['hash', 'metadata']:
for param in ["hash", "metadata"]:
if param in params_copy:
reformatted_params[param] = []
for k, v in params_copy[param].items():
reformatted_params[param].append(str(k) + ':' + str(v))
reformatted_params[param].append(str(k) + ":" + str(v))
del params_copy[param]

@@ -193,3 +225,3 @@ reformatted_params.update(params_copy)

while True:
resp = self._get("index", params=reformatted_params)
resp = self._get("index", params=reformatted_params, timeout=60)
handle_error(resp)

@@ -205,4 +237,4 @@ json_str = resp.json()

return
if len(json_str['records']) == page_size:
reformatted_params['start'] = json_str['records'][-1]['did']
if len(json_str["records"]) == page_size:
reformatted_params["start"] = json_str["records"][-1]["did"]
else:

@@ -213,4 +245,15 @@ # There's no more results

def create(
self, hashes, size, did=None, urls=None, file_name=None,
metadata=None, baseid=None, acl=None, urls_metadata=None, version=None):
self,
hashes,
size,
did=None,
urls=None,
file_name=None,
metadata=None,
baseid=None,
acl=None,
urls_metadata=None,
version=None,
authz=None,
):
"""Create a new entry in indexd

@@ -225,2 +268,3 @@

acl (list): access control list
authz (str): RBAC string
file_name (str): name of the file associated with a given UUID

@@ -247,3 +291,4 @@ metadata (dict): additional key value metadata for this entry

"acl": acl,
"version": version
"authz": authz,
"version": version,
}

@@ -253,19 +298,73 @@ if did:

resp = self._post(
"index/", headers={"content-type": "application/json"},
data=json_dumps(json), auth=self.auth)
"index/",
headers={"content-type": "application/json"},
data=json_dumps(json),
auth=self.auth,
)
return Document(self, resp.json()["did"])
def add_alias_for_did(self, alias, did):
"""
Adds an alias for a document id (did). Once an alias is created for
a did, the document can be retrieved by the alias using the
`global_get(alias)` function.
:param str alias:
The alias we want to assign to the document id.
:param str did:
The document id for the index record we want to alias.
:raises BaseIndexError:
Raised if aliasing operation fails.
"""
alias_payload = {"aliases": [{"value": alias}]}
resp = self._post(
"index/{}/aliases/".format(did),
headers={"content-type": "application/json"},
data=json.dumps(alias_payload),
auth=self.auth,
)
try:
return resp.json()
except ValueError as err:
reason = json.dumps(
{"error": "invalid json payload returned: {}".format(err)}
)
raise BaseIndexError(resp.status_code, reason)
# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias_for_did` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def create_alias(
self, record, size, hashes, release=None,
metastring=None, host_authorities=None, keeper_authority=None):
data = json_dumps({
'size': size,
'hashes': hashes,
'release': release,
'metastring': metastring,
'host_authorities': host_authorities,
'keeper_authority': keeper_authority
})
url = '/alias/' + record
headers = {'content-type': 'application/json'}
self,
record,
size,
hashes,
release=None,
metastring=None,
host_authorities=None,
keeper_authority=None,
):
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
data = json_dumps(
{
"size": size,
"hashes": hashes,
"release": release,
"metastring": metastring,
"host_authorities": host_authorities,
"keeper_authority": keeper_authority,
}
)
url = "alias/" + record
headers = {"content-type": "application/json"}
resp = self._put(url, headers=headers, data=data, auth=self.auth)

@@ -300,3 +399,5 @@ return resp.json()

rev_doc = self._post("index", current_did, json=new_doc.to_json(), auth=self.auth).json()
rev_doc = self._post(
"index", current_did, json=new_doc.to_json(), auth=self.auth
).json()
if rev_doc and "did" in rev_doc:

@@ -315,2 +416,3 @@ return Document(self, rev_doc["did"])

@retry_and_timeout_wrapper
def _get(self, *path, **kwargs):

@@ -321,2 +423,3 @@ resp = requests.get(self.url_for(*path), **kwargs)

@timeout_wrapper
def _post(self, *path, **kwargs):

@@ -327,2 +430,3 @@ resp = requests.post(self.url_for(*path), **kwargs)

@timeout_wrapper
def _put(self, *path, **kwargs):

@@ -333,2 +437,3 @@ resp = requests.put(self.url_for(*path), **kwargs)

@timeout_wrapper
def _delete(self, *path, **kwargs):

@@ -345,3 +450,2 @@ resp = requests.delete(self.url_for(*path), **kwargs)

class Document(object):
def __init__(self, client, did, json=None):

@@ -355,7 +459,25 @@ self.client = client

def __eq__(self, other_doc):
return self._doc == other_doc._doc
"""
equals `==` operator overload
It doesn't matter the order of the urls list. What matters is the
existence of the urls are the same on both sides.
"""
return self._sorted_doc == other_doc._sorted_doc
def __ne__(self, other_doc):
return self._doc != other_doc._doc
"""
not equals `!=` operator overload
It doesn't matter the order of the urls list. What matters is the
existence of the urls are the same on both sides.
"""
return self._sorted_doc != other_doc._sorted_doc
def __lt__(self, other_doc):
return self.did < other_doc.did
def __gt__(self, other_doc):
return self.did > other_doc.did
def __repr__(self):

@@ -368,7 +490,6 @@ """

"""
attributes = ', '.join([
'{}={}'.format(attr, self.__dict__[attr])
for attr in self._attrs
])
return '<Document(' + attributes + ')>'
attributes = ", ".join(
["{}={}".format(attr, self.__dict__[attr]) for attr in self._attrs]
)
return "<Document(" + attributes + ")>"

@@ -382,3 +503,5 @@ def _check_deleted(self):

if not self._fetched:
raise RuntimeError("Document must be fetched from the server before being rendered as json")
raise RuntimeError(
"Document must be fetched from the server before being rendered as json"
)
return self._doc

@@ -397,3 +520,3 @@

# set attributes to current Document
for k,v in json.items():
for k, v in json.items():
self.__dict__[k] = v

@@ -408,3 +531,3 @@ self._attrs = json.keys()

"""
return {k:v for k,v in self._doc.items() if k in UPDATABLE_ATTRS}
return {k: v for k, v in self._doc.items() if k in UPDATABLE_ATTRS}

@@ -415,2 +538,11 @@ @property

@property
def _sorted_doc(self):
"""Return the _doc object but with all arrays in sorted order.
This will allow us to compare dictionaries with lists correctly. We
only care about the contents of the arrays not the order of them.
"""
return recursive_sort(self._doc)
def patch(self):

@@ -424,7 +556,10 @@ """Update attributes in an indexd Document

self._check_deleted()
self.client._put("index", self.did,
params={"rev": self.rev},
headers={"content-type": "application/json"},
auth=self.client.auth,
data=json.dumps(self._doc_for_update()))
self.client._put(
"index",
self.did,
params={"rev": self.rev},
headers={"content-type": "application/json"},
auth=self.client.auth,
data=json.dumps(self._doc_for_update()),
)
self._load() # to sync new rev from server

@@ -434,5 +569,18 @@

self._check_deleted()
self.client._delete("index", self.did,
auth=self.client.auth,
params={"rev": self.rev})
self.client._delete(
"index", self.did, auth=self.client.auth, params={"rev": self.rev}
)
self._deleted = True
def recursive_sort(value):
"""
Sort all the lists in the dictionary recursively so that we can compare a
dictionary's contents being the same instead of comparing their order.
"""
if isinstance(value, dict):
return {key: recursive_sort(value[key]) for key in value.keys()}
elif isinstance(value, list):
return sorted([recursive_sort(element) for element in value])
else:
return value
class BaseIndexError(Exception):
'''
"""
Base index error.
'''
"""
def __init__(self, code, msg):

@@ -6,0 +7,0 @@ self.code = code

@@ -11,34 +11,31 @@ import sys

def create_record(host, port, form, size, urls, hashes, **kwargs):
'''
"""
Create a new record.
'''
resource = 'http://{host}:{port}/index/'.format(
host=host,
port=port,
)
"""
resource = "http://{host}:{port}/index/".format(host=host, port=port)
if size < 0:
raise ValueError('size must be non-negative')
raise ValueError("size must be non-negative")
urls_set = set(urls)
hash_set = set((h,v) for h,v in hashes)
hash_dict = {h:v for h,v in hash_set}
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error('multiple incompatible hashes specified')
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error('multiple values specified for {h}'.format(h=h))
raise ValueError('conflicting hashes provided')
logging.error("multiple values specified for {h}".format(h=h))
raise ValueError("conflicting hashes provided")
data = {
'form': form,
'size': size,
'urls': [u for u in urls_set],
'hashes': hash_dict,
"form": form,
"size": size,
"urls": [u for u in urls_set],
"hashes": hash_dict,
}

@@ -48,9 +45,11 @@

try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise BaseIndexError(res.status_code, res.text)
try: doc = res.json()
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({'error': 'invalid json payload returned'})
reason = json.dumps({"error": "invalid json payload returned"})
raise BaseIndexError(res.status_code, reason)

@@ -62,34 +61,31 @@

def config(parser):
'''
"""
Configure the create command.
'''
"""
parser.set_defaults(func=create_record)
parser.add_argument('form',
choices=['object', 'container', 'multipart'],
help='record format',
parser.add_argument(
"form", choices=["object", "container", "multipart"], help="record format"
)
parser.add_argument('--size',
required=True,
type=int,
help='size in bytes',
)
parser.add_argument("--size", required=True, type=int, help="size in bytes")
parser.add_argument('--hash',
parser.add_argument(
"--hash",
required=True,
nargs=2,
metavar=('TYPE', 'VALUE'),
action='append',
dest='hashes',
metavar=("TYPE", "VALUE"),
action="append",
dest="hashes",
default=[],
help='hash type and value',
help="hash type and value",
)
parser.add_argument('--url',
metavar='URL',
action='append',
dest='urls',
parser.add_argument(
"--url",
metavar="URL",
action="append",
dest="urls",
default=[],
help='known URLs associated with data',
help="known URLs associated with data",
)

@@ -12,33 +12,25 @@ import sys

def delete_record(host, port, did, rev, **kwargs):
'''
"""
Create a new record.
'''
resource = 'http://{host}:{port}/index/{did}'.format(
host=host,
port=port,
did=did,
)
"""
resource = "http://{host}:{port}/index/{did}".format(host=host, port=port, did=did)
params = {
'rev': rev,
}
params = {"rev": rev}
res = requests.delete(resource, params=params)
try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise BaseIndexError(res.status_code, res.text)
def config(parser):
'''
"""
Configure the delete command.
'''
"""
parser.set_defaults(func=delete_record)
parser.add_argument('did',
help='id of record to delete',
)
parser.add_argument("did", help="id of record to delete")
parser.add_argument('rev',
help='current revision of record',
)
parser.add_argument("rev", help="current revision of record")

@@ -5,2 +5,3 @@ import sys

import argparse
import warnings

@@ -12,21 +13,33 @@ import requests

# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def info(host, port, name, **kwargs):
'''
"""
Retrieve info by name.
'''
resource = 'http://{host}:{port}/alias/{name}'.format(
host=host,
port=port,
name=name,
"""
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
resource = "http://{host}:{port}/alias/{name}".format(
host=host, port=port, name=name
)
res = requests.get(resource)
try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try: doc = res.json()
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({'error': 'invalid json payload returned'})
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)

@@ -38,9 +51,7 @@

def config(parser):
'''
"""
Configure the info command.
'''
"""
parser.set_defaults(func=info)
parser.add_argument('name',
help='name of information to retrieve',
)
parser.add_argument("name", help="name of information to retrieve")
import sys
import json
import argparse
import warnings

@@ -10,43 +11,52 @@ import requests

def name_record(host, port, name, rev, size, hashes,
release, metadata, hosts, keeper, **kwargs):
'''
# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def name_record(
host, port, name, rev, size, hashes, release, metadata, hosts, keeper, **kwargs
):
"""
Alias a record.
'''
resource = 'http://{host}:{port}/alias/{name}'.format(
host=host,
port=port,
name=name,
"""
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
resource = "http://{host}:{port}/alias/{name}".format(
host=host, port=port, name=name
)
params = {
'rev': rev,
}
params = {"rev": rev}
if size is not None and size < 0:
raise ValueError('size must be non-negative')
raise ValueError("size must be non-negative")
host_set = set(hosts)
hash_set = set((h,v) for h,v in hashes)
hash_dict = {h:v for h,v in hash_set}
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error('multiple incompatible hashes specified')
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error('multiple values specified for {h}'.format(h=h))
raise ValueError('conflicting hashes provided')
logging.error("multiple values specified for {h}".format(h=h))
raise ValueError("conflicting hashes provided")
data = {
'size': size,
'hashes': hash_dict,
'release': release,
'metadata': metadata,
'host_authorities': [h for h in host_set],
'keeper_authority': keeper,
"size": size,
"hashes": hash_dict,
"release": release,
"metadata": metadata,
"host_authorities": [h for h in host_set],
"keeper_authority": keeper,
}

@@ -56,9 +66,11 @@

try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try: doc = res.json()
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({'error': 'invalid json payload returned'})
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)

@@ -70,49 +82,37 @@

def config(parser):
'''
"""
Configure the name command.
'''
"""
parser.set_defaults(func=name_record)
parser.add_argument('name',
help='name to assign',
)
parser.add_argument("name", help="name to assign")
parser.add_argument('rev',
nargs='?',
help='revision of name',
)
parser.add_argument("rev", nargs="?", help="revision of name")
parser.add_argument('--size',
default=None,
type=int,
help='size of underlying data',
parser.add_argument(
"--size", default=None, type=int, help="size of underlying data"
)
parser.add_argument('--hash',
parser.add_argument(
"--hash",
nargs=2,
metavar=('TYPE', 'VALUE'),
action='append',
dest='hashes',
metavar=("TYPE", "VALUE"),
action="append",
dest="hashes",
default=[],
help='hash type and value',
help="hash type and value",
)
parser.add_argument('--release',
choices=['public', 'private', 'controlled'],
help='data release type',
parser.add_argument(
"--release",
choices=["public", "private", "controlled"],
help="data release type",
)
parser.add_argument('--metadata',
help='metadata string',
)
parser.add_argument("--metadata", help="metadata string")
parser.add_argument('--host',
action='append',
dest='hosts',
default=[],
help='host authority',
parser.add_argument(
"--host", action="append", dest="hosts", default=[], help="host authority"
)
parser.add_argument('--keeper',
help='data keeper authority',
)
parser.add_argument("--keeper", help="data keeper authority")

@@ -12,20 +12,18 @@ import sys

def retrieve_record(host, port, did, **kwargs):
'''
"""
Retrieve a record by id.
'''
resource = 'http://{host}:{port}/index/{did}'.format(
host=host,
port=port,
did=did,
)
"""
resource = "http://{host}:{port}/index/{did}".format(host=host, port=port, did=did)
res = requests.get(resource)
try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try: doc = res.json()
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({'error': 'invalid json payload returned'})
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)

@@ -37,9 +35,7 @@

def config(parser):
'''
"""
Configure the retrieve command.
'''
"""
parser.set_defaults(func=retrieve_record)
parser.add_argument('did',
help='id of record to retrieve',
)
parser.add_argument("did", help="id of record to retrieve")

@@ -5,2 +5,3 @@ import sys

import argparse
import warnings

@@ -13,48 +14,42 @@ import requests

def search_record(host, port, limit, start, size, hashes, **kwargs):
'''
"""
Finds records matching specified search criteria.
'''
"""
if size is not None and size < 0:
raise ValueError('size must be non-negative')
raise ValueError("size must be non-negative")
if limit is not None and limit < 0:
raise ValueError('limit must be non-negative')
raise ValueError("limit must be non-negative")
hash_set = set((h,v) for h,v in hashes)
hash_dict = {h:v for h,v in hash_set}
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error('multiple incompatible hashes specified')
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error('multiple values specified for {h}'.format(h=h))
raise ValueError('conflicting hashes provided')
logging.error("multiple values specified for {h}".format(h=h))
hashes = [':'.join([h,v]) for h,v in hash_dict.items()]
raise ValueError("conflicting hashes provided")
resource = 'http://{host}:{port}/index/'.format(
host=host,
port=port,
)
hashes = [":".join([h, v]) for h, v in hash_dict.items()]
params = {
'limit': limit,
'start': start,
'hash': hashes,
'size': size,
}
resource = "http://{host}:{port}/index/".format(host=host, port=port)
params = {"limit": limit, "start": start, "hash": hashes, "size": size}
res = requests.get(resource, params=params)
try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try: doc = res.json()
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({'error': 'invalid json payload returned'})
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)

@@ -64,49 +59,56 @@

# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def search_names(host, port, limit, start, size, hashes, **kwargs):
'''
"""
Finds records matching specified search criteria.
'''
"""
warnings.warn(
(
"This function is deprecated. For creating aliases for indexd "
"records, prefer using the `add_alias_for_did` function, which "
"interacts with the new `/index/{GUID}/aliases` endpoint."
),
DeprecationWarning,
)
if size is not None and size < 0:
raise ValueError('size must be non-negative')
raise ValueError("size must be non-negative")
if limit is not None and limit < 0:
raise ValueError('limit must be non-negative')
raise ValueError("limit must be non-negative")
hash_set = set((h,v) for h,v in hashes)
hash_dict = {h:v for h,v in hash_set}
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error('multiple incompatible hashes specified')
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error('multiple values specified for {h}'.format(h=h))
raise ValueError('conflicting hashes provided')
logging.error("multiple values specified for {h}".format(h=h))
hashes = [':'.join([h,v]) for h,v in hash_dict.items()]
raise ValueError("conflicting hashes provided")
resource = 'http://{host}:{port}/alias/'.format(
host=host,
port=port,
)
hashes = [":".join([h, v]) for h, v in hash_dict.items()]
params = {
'limit': limit,
'start': start,
'size': size,
'hashes': hashes,
}
resource = "http://{host}:{port}/alias/".format(host=host, port=port)
params = {"limit": limit, "start": start, "size": size, "hashes": hashes}
res = requests.get(resource, params=params)
try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise errors.BaseIndexError(res.status_code, res.text)
try: doc = res.json()
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({'error': 'invalid json payload returned'})
reason = json.dumps({"error": "invalid json payload returned"})
raise errors.BaseIndexError(res.status_code, reason)

@@ -118,45 +120,35 @@

def config(parser):
'''
"""
Configure the search command.
'''
"""
parser.set_defaults(func=search_record)
parser.add_argument('--names',
action='store_const',
parser.add_argument(
"--names",
action="store_const",
const=search_names,
dest='func',
help='search names instead of records',
dest="func",
help="search names instead of records",
)
parser.add_argument('--limit',
default=None,
type=int,
help='limit on number of ids to retrieve',
parser.add_argument(
"--limit", default=None, type=int, help="limit on number of ids to retrieve"
)
parser.add_argument('--start',
default=None,
help='starting id or alias',
)
parser.add_argument("--start", default=None, help="starting id or alias")
parser.add_argument('--size',
default=None,
type=int,
help='filter based on size',
)
parser.add_argument("--size", default=None, type=int, help="filter based on size")
parser.add_argument('--hash',
parser.add_argument(
"--hash",
nargs=2,
metavar=('TYPE', 'VALUE'),
action='append',
dest='hashes',
metavar=("TYPE", "VALUE"),
action="append",
dest="hashes",
default=[],
help='filter based on hash values',
help="filter based on hash values",
)
parser.add_argument('--url',
action='append',
dest='urls',
default=[],
help='filter based on urls',
parser.add_argument(
"--url", action="append", dest="urls", default=[], help="filter based on urls"
)

@@ -11,49 +11,41 @@ import sys

def update_record(host, port, did, rev, size, hashes, urls, **kwargs):
'''
"""
Update a record.
'''
resource = 'http://{host}:{port}/index/{did}'.format(
host=host,
port=port,
did=did,
)
"""
resource = "http://{host}:{port}/index/{did}".format(host=host, port=port, did=did)
params = {
'rev': rev,
}
params = {"rev": rev}
if size < 0:
raise ValueError('size must be non-negative')
raise ValueError("size must be non-negative")
urls_set = set(urls)
hash_set = set((h,v) for h,v in hashes)
hash_dict = {h:v for h,v in hash_set}
hash_set = set((h, v) for h, v in hashes)
hash_dict = {h: v for h, v in hash_set}
if len(hash_dict) < len(hash_set):
logging.error('multiple incompatible hashes specified')
logging.error("multiple incompatible hashes specified")
for h in hash_dict.items():
hash_set.remove(h)
for h, _ in hash_set:
logging.error('multiple values specified for {h}'.format(h=h))
raise ValueError('conflicting hashes provided')
logging.error("multiple values specified for {h}".format(h=h))
data = {
'size': size,
'urls': [u for u in urls_set],
'hashes': hash_dict,
}
raise ValueError("conflicting hashes provided")
data = {"size": size, "urls": [u for u in urls_set], "hashes": hash_dict}
res = requests.put(resource, params=params, json=data)
try: res.raise_for_status()
try:
res.raise_for_status()
except Exception as err:
raise BaseIndexError(res.status_code, res.text)
try: doc = res.json()
try:
doc = res.json()
except ValueError as err:
reason = json.dumps({'error': 'invalid json payload returned'})
reason = json.dumps({"error": "invalid json payload returned"})
raise BaseIndexError(res.status_code, reason)

@@ -65,36 +57,30 @@

def config(parser):
'''
"""
Configure the update command.
'''
"""
parser.set_defaults(func=update_record)
parser.add_argument('did',
help='document id',
)
parser.add_argument("did", help="document id")
parser.add_argument('rev',
help='document revision',
)
parser.add_argument("rev", help="document revision")
parser.add_argument('--size',
required=True,
type=int,
help='size in bytes',
)
parser.add_argument("--size", required=True, type=int, help="size in bytes")
parser.add_argument('--hash',
parser.add_argument(
"--hash",
required=True,
nargs=2,
metavar=('TYPE', 'VALUE'),
action='append',
dest='hashes',
help='hash type and value',
metavar=("TYPE", "VALUE"),
action="append",
dest="hashes",
help="hash type and value",
)
parser.add_argument('--url',
metavar='URL',
action='append',
dest='urls',
parser.add_argument(
"--url",
metavar="URL",
action="append",
dest="urls",
default=[],
help='known URLs associated with data',
help="known URLs associated with data",
)
Metadata-Version: 1.0
Name: indexclient
Version: 1.5.8
Version: 2.1.0
Summary: UNKNOWN

@@ -5,0 +5,0 @@ Home-page: UNKNOWN

+129
-12

@@ -1,6 +0,6 @@

Index
Indexclient
===
![version](https://img.shields.io/badge/version-0.0.1-orange.svg?style=flat) [![Apache license](http://img.shields.io/badge/license-Apache-blue.svg?style=flat)](LICENSE) [![Travis](https://travis-ci.org/LabAdvComp/index.svg?branch=master)](https://travis-ci.org/LabAdvComp/index)
![version](https://img.shields.io/badge/version-2.0.0-green.svg?style=flat) [![Apache license](http://img.shields.io/badge/license-Apache-blue.svg?style=flat)](LICENSE) [![Travis](https://travis-ci.org/uc-cdis/indexclient.svg?branch=master)](https://travis-ci.org/uc-cdis/indexclient)
Index is a prototype data indexing and tracking client. It is intended to
Indexclient is a prototype data indexing and tracking client. It is intended to
provide a simple means of interactively investigating

@@ -77,4 +77,6 @@ [indexd](https://github.com/LabAdvComp/indexd) deployments. It is built upon

## Making Queries
All queries to the index are made through HTTP using JSON data payloads.

@@ -86,20 +88,135 @@ This gives a simple means of interaction that is easily accessible to any

### Create a record
***TODO***
### Create a record
### Name a record
***TODO***
#### Method: `create`
### Retrieve a record
Example:
***TODO***
```python
indexclient.create(
hashes = {'md5': ab167e49d25b488939b1ede42752458b'},
size = 5,
# optional arguments
acl = ["a", "b"]
)
```
### Update a record
***TODO***
### Retrieve a record
#### Method: `get`
Example:
```python
indexclient.get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
```
#### Method: `global_get`
Example:
```python
indexclient.global_get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
```
or
```python
indexclient.global_get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e", no_dist=True)
```
`global_get` can also be used to retrieve records by alias. See [Add an alias for a record](#add-an-alias-for-a-record).
```python
# Retrieve a document by its alias, "10.1000/182"
doc = indexclient.global_get("10.1000/182")
print(doc.did) # >> "g.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e"
```
#### Method: `get_with_params`
Example:
```python
params = {
'hashes': {'md5': ab167e49d25b488939b1ede42752458b'},
'size': 5
# or any other params (metadata, acl, authz, etc.)
}
indexclient.get_with_params(params)
```
### Retrieve multiple records
#### Method: `bulk_request`
Example:
```python
dids = [
"03eed607-acb0-4532-b0ee-9e3766b1aa6e",
"15684515-15b0-4532-b0ee-9e3766b65515",
"03ee4857-acb0-4123-b0ee-9e3766bffa23",
"1258d607-acb0-4532-b0ee-9e3766bffa23"
]
indexclient.bulk_request(dids)
```
### Update a record
First: get a Document object of the desired record with one of the get methods
Second: Update any of the records updatable attributes.
- the format to do this is: `doc.attr = value`
- eg: `doc.file_name = new_file_name`
- Updatable attributes are: file_name urls, version, metadata, acl, authz, urls_metadata, uploader
Lastly: Update all the local changes that were made to indexd using the
Document patch method: doc.patch()
Example:
```python
doc = indexclient.get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e"')
# or any other get method (global_get, etc.)
doc.metadata["dummy_field"] = "dummy var"
doc.acl = ['a', 'b']
doc.version = '2'
doc.patch()
```
### Delete a record
***TODO***
First: get a Document object of the desired record with one of the get methods
Second: Delete the record from indexd with the delete method: `doc.delete()`
Lastly: Check if the record was deleted with: `if doc._deleted`
Example:
```python
doc = indexclient.get("dg.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
# or any other get method (global_get, etc.)
doc.delete()
if doc._deleted == False:
return "Record is not deleted"
```
### Add an alias for a record
You can use `indexclient` to create aliases for documents in `indexd`, which enable you to retrieve documents by the alias instead of by the Document identifier (`did` / `GUID`). Aliases can be created using `indexclient.add_alias_for_did(alias=alias, did=did)` and can be retrieved using `indexclient.global_get(alias)`.
Example:
```python
res = indexclient.add_alias_for_did("10.1000/182", "g.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e")
if res.status_code != 200:
# alias creation failed -- handle error
doc = indexclient.global_get("10.1000/182")
print(doc.did) # >> "g.1234/03eed607-acb0-4532-b0ee-9e3766b1aa6e"
```

@@ -0,13 +1,26 @@

from subprocess import check_output
from setuptools import setup
def get_version():
# https://github.com/uc-cdis/dictionaryutils/pull/37#discussion_r257898408
try:
tag = check_output(
["git", "describe", "--tags", "--abbrev=0", "--match=[0-9]*"]
)
return tag.decode("utf-8").strip("\n")
except Exception:
raise RuntimeError(
"The version number cannot be extracted from git tag in this source "
"distribution; please either download the source from PyPI, or check out "
"from GitHub and make sure that the git CLI is available."
)
setup(
name='indexclient',
version='1.5.8',
packages=[
'indexclient',
'indexclient.parsers',
],
install_requires=[
'requests>=2.5.2,<3.0.0',
],
name="indexclient",
version='2.1.0',
packages=["indexclient", "indexclient.parsers"],
install_requires=["requests>=2.5.2,<3.0.0"],
)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
include LICENSE
include NOTICE
include Pipfile
include Pipfile.lock
Copyright 2015 University of Chicago
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
indexclient = {editable = true,path = "."}
[requires]
python_version = "2.7"
{
"_meta": {
"hash": {
"sha256": "b17bba0d5cb06e637ce57d82a0b020345f2840d6596ccebe2bd3b12c6be73781"
},
"pipfile-spec": 6,
"requires": {
"python_version": "2.7"
},
"sources": [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": true
}
]
},
"default": {
"certifi": {
"hashes": [
"sha256:47f9c83ef4c0c621eaef743f133f09fa8a74a9b75f037e8624f83bd1b6626cb7",
"sha256:993f830721089fef441cdfeb4b2c8c9df86f0c63239f06bd025a76a7daddb033"
],
"version": "==2018.11.29"
},
"chardet": {
"hashes": [
"sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae",
"sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"
],
"version": "==3.0.4"
},
"idna": {
"hashes": [
"sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407",
"sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c"
],
"version": "==2.8"
},
"indexclient": {
"editable": true,
"path": "."
},
"requests": {
"hashes": [
"sha256:502a824f31acdacb3a35b6690b5fbf0bc41d63a24a45c4004352b0242707598e",
"sha256:7bf2a778576d825600030a110f3c0e3e8edc51dfaafe1c146e39a2027784957b"
],
"version": "==2.21.0"
},
"urllib3": {
"hashes": [
"sha256:61bf29cada3fc2fbefad4fdf059ea4bd1b4a86d2b6d15e1c7c0b582b9752fe39",
"sha256:de9529817c93f27c8ccbfead6985011db27bd0ddfcdb2d86f3f663385c6a9c22"
],
"version": "==1.24.1"
}
},
"develop": {}
}