PK ! G cranial/connectors/__init__.py"""
Expose your connectors here so they are all importable from cranial.connectors.
"""
from cranial.connectors.base import Connector
from cranial.connectors.local import Connector as LocalConnector
from cranial.connectors.s3 import InMemoryConnector as S3InMemoryConnector
PK ! +) cranial/connectors/base.pyimport io
import os
from tempfile import mkstemp
from concurrent import futures
from concurrent.futures import Future, ThreadPoolExecutor
from cranial.parsers import line
class Connector():
def __init__(self, base_address='', binary=True, do_read=False):
self.base_address = base_address
self.binary = binary
self.do_read = do_read
def iterator(self, target: Any) -> iter:
"""Get one or more IOstreams and iterate over them yielding lines."""
if type(target) == list:
return self.generate_from_list(target)
else:
f = self.getFuture(target)
return self.generate(f)
def generate(self, future_item):
for l in line.Parser(f.result()):
yield l
def generate_from_list(self, l: List):
# @ToDo
#getMultiple on all items, start returning whatever item arrives first.
done = set()
while len(done) < len(d):
for key in d:
if not (key in done):
try:
data = response[key].result(1)
for l in line.Parser(data):
yield l
done.add(key)
except futures.TimeoutError:
pass
except futures.CancelledError:
response[key] = False
done.add(key)
return response
def toStream(self, data):
if type(data) is str:
return io.StringIO(data)
elif type(data) is bytes:
return io.BytesIO(data)
else:
raise Exception('Not implemented for data type: {}'.format(
type(data)))
def get_tmp_file(self):
fd, local_path = mkstemp()
os.close(fd)
return fd, local_path
def get(self, name=None) -> io.BytesIO:
"""Return an IOstream."""
raise Exception('Not Implemented')
def put(self, stream: io.BytesIO, name: str = None) -> bool:
"""Return True if successful."""
raise Exception('Not Implemented')
def executor(self):
if not hasattr(self, 'pool'):
self.pool = ThreadPoolExecutor()
return self.pool
def _doFuture(self, fn: callable, *args, **kwargs) -> Future:
return self.executor().submit(fn, *args, **kwargs)
def getFuture(self, *args, **kwargs) -> Future:
return self._doFuture(self.get, *args, **kwargs)
def putFuture(self, *args, **kwargs) -> Future:
return self._doFuture(self.put, *args, **kwargs)
def _doMultiple(self, fn: callable, d: dict, blocking=True, **kwargs):
"""Takes a dict of keys to argument to pass to fn.
Returns dict of Futures if 'blocking' is set False. Otherwise IOStreams.
"""
response = {}
for key in d:
args = d[key]
# Gracefully accept single arguments as-is.
if type(args) is not list:
args = [args]
response[key] = fn(*args, **kwargs)
if not blocking:
return response
done = set()
while len(done) < len(d):
for key in d:
if not (key in done):
try:
data = response[key].result(1)
response[key] = data
done.add(key)
except futures.TimeoutError:
pass
except futures.CancelledError:
response[key] = False
done.add(key)
return response
def getMultiple(self, d: dict, blocking=True, **kwargs):
return self._doMultiple(self.getFuture, d, blocking, **kwargs)
def putMultiple(self, d: dict, blocking=True, **kwargs):
return self._doMultiple(self.putFuture, d, blocking, **kwargs)
def __str__(self):
ss = [str(self.__class__).split("'")[1]]
for attr in dir(self):
if (not attr.startswith("_")) and (not hasattr(getattr(self, attr), '__call__')):
ss.append("{} = {}".format(attr, getattr(self, attr))[:100])
return '\t'.join(ss)
PK ! ? ( cranial/connectors/googlecloudstorage.pyimport logging
import io
import os
from google.cloud.storage import Client, Blob
from google.oauth2 import service_account
from cranial.connectors import base
from cranial.common import logger
log = logger.get('GOOGLECLOUDSTORAGE_LOGLEVEL', name='gcs_connector')
class InMemoryConnector(base.Connector):
def __init__(self, bucket, prefix='', binary=True, do_read=False,
credentials=None, project=None):
super().__init__(base_address=prefix, binary=binary, do_read=do_read)
params = {'project': project}
if credentials:
creds = service_account.Credentials.from_service_account_info(
credentials)
params['credentials'] = creds
self.bucket = Client(**params).get_bucket(bucket)
self.bucket_name = bucket
def get(self, name=None):
"""
Get a bytes stream of an object
Parameters
----------
name
if None, prefix will be used as a key name, otherwise name will be added to prefix after '/' separator
Returns
-------
bytes stream with key's data, or an empty stream if errors occurred
"""
key = self.base_address if name is None else os.path.join(self.base_address, name)
key = key.strip('/')
try:
blob = Blob(key, self.bucket)
filestream = io.BytesIO()
blob.download_to_file(filestream)
filestream.seek(0)
log.info("Getting {} bytes from \tbucket={}\tkey={}".format(
blob.size, self.bucket_name, key))
self.metadata = blob.metadata
except Exception as e:
log.error("{}\tbucket={}\tkey={}".format(e, self.bucket_name, key))
if log.level == logging.DEBUG:
raise e
if self.do_read:
asbytes = filestream.read()
if not self.binary:
return asbytes.decode()
else:
return asbytes
return filestream
def put(self, source, name=None):
"""
Parameters
----------
source
name
Returns
-------
"""
if isinstance(source, io.BytesIO):
filebuff = io.BufferedReader(source)
elif isinstance(source, (str, bytes)):
filebuff = io.BufferedReader(io.BytesIO(source))
else:
log.error('Source should be either a string, or bytes or io.BytesIO, got {}'.format(type(source)))
return False
key = self.base_address if name is None else os.path.join(
self.base_address, name)
key = key.strip('/')
try:
blob = Blob(key, self.bucket)
blob.upload_from_file(filebuff, rewind=True)
log.info("Uploaded {} bytes to \tbucket={}\tkey={}".format(
len(source), self.bucket_name, key))
return True
except Exception as e:
log.error("{}\tbucket={}\tkey={}".format(e, self.bucket, key))
return False
PK ! Ȝz cranial/connectors/http.pyfrom requests_futures.sessions import FuturesSession
from cranial.connectors import base
class Connector(base.Connector):
r"""Connector for getting data via HTTP. Upload not yet implemented.
>>> stream = Connector().get('http://httpbin.org/html')
>>> next(stream).startswith('')
True
>>> r = Connector('http://httpbin.org').getMultiple({'rabbit': 'image/png', 'grenade': 'bytes/10'}, binary=True)
>>> next(r['rabbit'])
b'\x89PNG\r\n'
"""
def __init__(self, host: str = None):
self.session = FuturesSession()
# Ensure host ends in '/' if given.
self.url_host = host if host is None or host.endswith('/') else host+'/'
def get(self, url, binary=False):
url = url if not self.url_host else self.url_host + url
r = self.getFuture(url).result()
return self.toStream(r.content if binary else r.text)
def getFuture(self, url):
url = url if not self.url_host else self.url_host + url
return self.session.get(url)
def getMultiple(self, d, blocking=True, binary=False):
result = super(Connector, self).getMultiple(d, blocking)
if not(blocking):
return result
for key in result:
r = result[key]
result[key] = self.toStream(r.content if binary else r.text)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
PK ! $.
cranial/connectors/local.pyfrom datetime import datetime
import io
import os
from tempfile import mkstemp
from cranial.connectors import base
from cranial.common import logger
log = logger.get(name='local_fetchers') # streaming log
def file_readlines(fp, delete_after=False):
"""
memory efficient iterator to read lines from a file (readlines() method reads whole file)
Parameters
----------
fp
path to a decompressed file downloaded from s3 key
delete_after
delete file after it was read
Returns
-------
generator of lines
"""
with open(fp) as f:
while True:
line = f.readline()
if line:
yield line
else:
break
if delete_after:
try:
os.unlink(fp)
except Exception as e:
log.warning(e)
class Connector(base.Connector):
def __init__(self, path: str = '', binary=True, do_read=False) -> None:
super().__init__(base_address=path, binary=binary, do_read=do_read)
self._open_files = [] # type: List[FileHandle]
def get(self, name=None):
if name.startswith('/'):
name = name[1:]
filepath = self.base_address if name is None else os.path.join(self.base_address, name)
try:
mode = 'rb' if self.binary else 'r'
fh = open(filepath, mode)
self._open_files.append(fh)
res = fh
self.metadata = {
'LastModified': datetime.utcfromtimestamp(
os.path.getmtime(filepath))}
log.info("Opened \t{}".format(filepath))
except Exception as e:
log.error("{}\tbase_address={}\tname={}\tfilepath={}".format(
e, self.base_address, name, filepath))
res = io.BytesIO() if self.binary else io.StringIO()
if self.do_read:
res = res.read()
return res
def put(self, source, name: str = None) -> bool:
filepath = self.base_address if name is None else os.path.join(self.base_address, name)
dir_path = os.path.split(filepath)[0]
if len(dir_path) > 0:
os.makedirs(dir_path, exist_ok=True)
if isinstance(source, io.IOBase):
source = source.read()
elif isinstance(source, (str, bytes)):
pass
else:
log.error('Source should be either a string, bytes or a readable buffer, got {}'.format(type(source)))
return False
try:
mode = 'wb' if self.binary else 'w'
# first write to a temp file
_, local_path = self.get_tmp_file()
with open(local_path, mode) as f:
f.write(source)
# then rename temp file to a proper name
os.rename(local_path, filepath)
log.info("wrote to \t{}".format(filepath))
return True
except Exception as e:
log.error("{}\tbase_address={}\tname={}".format(e, self.base_address, name))
return False
def get_tmp_file(self):
fd, local_path = mkstemp(dir=self.base_address)
os.close(fd)
return fd, local_path
def __del__(self):
[fh.close() for fh in self._open_files]
if __name__ == "__main__":
import doctest
doctest.testmod()
PK ! HM M cranial/connectors/s3.pyimport io
import logging
import os
import shutil
import subprocess
import tempfile
from typing import Dict
import boto3
from cranial.connectors import base
from cranial.common import logger
log = logger.get('S3_LOGLEVEL', name='s3_fetchers')
SOURCE_DIR = 'storage/source'
TARGET_DIR = 'storage/target'
MODEL_DIR = 'storage/model'
def cleanup_temp_data():
"""
delete temp dirs
"""
try:
shutil.rmtree(SOURCE_DIR)
log.info("Removed {}".format(SOURCE_DIR))
except Exception as e:
log.info(e)
try:
shutil.rmtree(TARGET_DIR)
log.info("Removed {}".format(TARGET_DIR))
except Exception as e:
log.info(e)
try:
shutil.rmtree(MODEL_DIR)
log.info("Removed {}".format(MODEL_DIR))
except Exception as e:
log.info(e)
def prepare_s3_prefix(bucket, pre_date_part, y=None, mo=None, d=None, h=None, after_date_part=''):
"""
compose an s3 path from given parts and date values
example:
{bucket}/{pre_date_part}/mo={y}-{mo}/day={d}/hour={h}/after_date_part
Parameters
----------
bucket
bucket name, may include "s3://"
pre_date_part
part of the path before date strings
y
year number
mo
month number
d
day number
h
hour number
after_date_part
part of the path after date strings
Returns
-------
composed s3 path
"""
if not bucket.startswith('s3://'): bucket = 's3://' + bucket
s = '/'.join([bucket.strip('/'), pre_date_part.strip('/')])
if y is not None and mo is not None:
s += '/mo={y}-{mo}'.format(y=y, mo=mo)
if d is not None:
s += '/day={d}'.format(d=d)
if h is not None:
s += '/hour={h}'.format(h=h)
if len(after_date_part) > 0:
s += '/' + after_date_part
return s
def read_key(key, bucket, decode=True, verbose=False):
"""
The intended use is within a map function, so to change bucket and verbosity is not extremely simple and needs
some functools (partial?)
Parameters - self explanatory
Returns - contents of the s3 key, decoded into utf8 string
"""
if verbose:
log.info('reading {}'.format(key))
try:
b_str = boto3.resource('s3').Bucket(bucket).Object(key).get()['Body'].read()
except Exception as e:
log.error("{}:{}\t{}".format(bucket, key, e))
return None
return b_str.decode() if decode else b_str
def key_download_decompress(bucket, key, force_decompress=False):
"""
First step in getting events from s3 key:
- download a key into a temp file
- decompress on disk
Returns
-------
name of the decompressed temp file or None if failed
"""
fp = tempfile.mkstemp(suffix='.gz')[1]
boto3.resource('s3').Bucket(bucket).download_file(key, fp)
log.info("downloaded {}/{} to {}".format(bucket, key, fp))
if key.endswith('.gz') or force_decompress:
# @TODO Replace with gzip module.
p = subprocess.run(['gunzip', fp, '-f'], stderr=subprocess.PIPE)
if p.returncode == 0:
log.info('decompressed {}'.format(fp))
return fp[:-3]
else:
log.warning(p.stderr)
return None
class S3Connector(base.Connector):
def __init__(self, bucket: str, prefix='') -> None:
self.bucket = bucket
self.prefix = prefix
self.cache = {} # type: Dict[str, str]
log.info('s3.S3Connector downloads whole files to local disk '
+ 'before use. Consider s3.InMemoryConnector instead.')
def get(self, s3_path, binary=False, redownload=False):
if not redownload:
try:
local_path = self.cache[s3_path]
return open(local_path, 'r' + 'b' if binary else '')
except Exception as e:
log.warn('S3 object {} not in cache: {}'.format(s3_path, e))
local_path = key_download_decompress(self.bucket, self.prefix + s3_path)
self.cache[s3_path] = local_path
return open(local_path, 'r' + 'b' if binary else '')
def put(self, source, name=None):
fname = name if name else source.split('/')[-1]
bucket = boto3.resource('s3').Bucket(self.bucket)
if type(source) is str:
bucket.upload_file(
self.prefix + fname, source)
return True
elif type(source) is io.BytesIO:
bucket.upload_fileobj(
self.prefix + fname, source)
return True
else:
raise Exception(
"Can't put source data type {}. Pass BytesIO or string path to a local file.".format(type(source)))
class InMemoryConnector(base.Connector):
def __init__(self, bucket, prefix='', binary=True, do_read=False,
credentials={}):
super(InMemoryConnector, self).__init__(base_address=prefix, binary=binary, do_read=do_read)
self.credentials = credentials
self.bucket = bucket
def get(self, name=None):
"""
Get a bytes stream of an s3 key
Parameters
----------
name
if None, prefix will be used as a key name, otherwise name will be added to prefix after '/' separator
Returns
-------
bytes stream with key's data, or an empty stream if errors occurred
"""
key = self.base_address if name is None else os.path.join(self.base_address, name)
key = key.strip('/')
try:
res = boto3.resource('s3', **self.credentials).Bucket(self.bucket).Object(key).get()
loglevel = log.warning if res['ContentLength'] == 0 else log.debug
loglevel("Getting {} bytes from \tbucket={}\tkey={}".format(res['ContentLength'], self.bucket, key))
body = res.pop('Body')
self.metadata = res
except Exception as e:
log.error("{}\tbucket={}\tkey={}".format(e, self.bucket, key))
if log.level == logging.DEBUG:
raise e
body = io.BytesIO()
if self.do_read:
body = body.read()
if not self.binary:
body = body.decode()
return body
def put(self, source, name=None):
"""
Parameters
----------
source
name
Returns
-------
"""
if isinstance(source, io.BytesIO):
source = source.read()
elif isinstance(source, (str, bytes)):
pass
else:
log.error('Source should be either a string, or bytes or io.BytesIO, got {}'.format(type(source)))
return False
key = self.base_address if name is None else os.path.join(self.base_address, name)
key = key.strip('/')
try:
res = boto3.resource('s3').Bucket(self.bucket).Object(key).put(Body=source)
log.info("Uploaded {} bytes to \tbucket={}\tkey={}".format(len(source), self.bucket, key))
return res['ResponseMetadata']['HTTPStatusCode'] == 200
except Exception as e:
log.error("{}\tbucket={}\tkey={}".format(e, self.bucket, key))
return False
PK ! X@ ' cranial/datastore/adapters/cassandra.pyfrom cassandra.encoder import Encoder
from cranial.common import logger
log = logger.get()
class Adapter():
def __init__(self, session):
self.session = session
self.res = None
# Use Cassandra Encoder to prevent SQL Injection
self.encoder = Encoder()
def sanitize(self, q, params):
"""
Basic prevention against SQL Injection.
>>> adapter = CassandraAdapter(None)
>>> adapter.sanitize('SQL {}', ["injection'; DROP DATABASE;--"])
"SQL 'injection''; DROP DATABASE;--'"
"""
sanitized = map(self.encoder.cql_encode_all_types, params)
return q.replace('?', '{}').format(*list(sanitized))
def execute(self, q, params=None, executor=None):
if executor is None:
executor = self.session.execute
try:
if type(q) is str and params is not None and len(params):
q = self.sanitize(q, params)
self.res = executor(q)
else:
self.res = executor(q, params)
except Exception as e:
log.error('Exception {} on {}; {}'.format(e, q, str(params)))
raise e
self.rowcount = len(self.res.current_rows) if hasattr(self.res, 'current_rows') else None
columns = getattr(self.res, 'column_names', [])
self.description = [[c] for c in columns] if columns is not None else []
return self.res
def execute_async(self, q, params=None):
return self.execute(q, params, executor=self.session.execute_async)
def get_async(self):
# Block for Async results...
if hasattr(self.res, 'result'):
self.res = self.res.result()
self.rowcount = len(self.res.current_rows)
columns = getattr(self.res, 'column_names', [])
self.description = [[c] for c in columns] if columns is not None else []
def fetchone(self):
self.get_async()
if self.rowcount:
return self.res[0]
else:
# @ToDo This seems to assume KeyValueDB. We should generalize.
raise KeyError('Key not found.')
def fetchall(self):
self.get_async()
return self.res
def __getattr__(self, name):
""" Proxy anything else to the session object, for cases where DBAPI2
compatible things already exist."""
return getattr(self.session, name)
# Alias
CassandraAdapter = Adapter
PK ! x x " cranial/datastore/adapters/psql.py'''
Helpers for postgres/redshift.
'''
import os
from select import select
from typing import Dict, List, Optional # noqa
import psycopg2
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
from cranial.common import logger
log = logger.get()
default_config = {
'keepalives': '1',
'keepalives_idle': '6',
'keepalives_interval': '20',
'keepalives_count': '1'} # type: Dict[str, Optional[str]]
def wait_select_inter(conn):
"""
cancel query by crtl-c
http://initd.org/psycopg/articles/2014/07/20/cancelling-postgresql-statements-python/
"""
while 1:
try:
state = conn.poll()
if state == POLL_OK:
break
elif state == POLL_READ:
select([conn.fileno()], [], [])
elif state == POLL_WRITE:
select([], [conn.fileno()], [])
else:
raise conn.OperationalError(
"bad state from poll: %s" % state)
except KeyboardInterrupt:
conn.cancel()
# the loop will be broken by a server error
continue
psycopg2.extensions.set_wait_callback(wait_select_inter)
credentials = None # type: Optional[List]
def _split_parts(parts: List[str]) -> Dict[str, Optional[str]]:
c = default_config.copy()
if len(parts) < 5:
return c
c['host'], c['port'], c['dbname'], c['user'], c['password'] = parts
for key, value in c.items():
if value == '*':
c[key] = None
else:
c[key] = value
return c
def get_credentials(pgpass='~/.pgpass', append=False):
global credentials
if credentials is None or append:
credentials = credentials or []
with open(os.path.expanduser(pgpass)) as f:
for line in f.readlines():
line = line.strip('\n')
parts = line.split(":")
connect_params = _split_parts(parts)
credentials.append(connect_params)
return credentials
def find_credentials(credentials_file='~/.pgpass', **kwargs) -> Dict[str, str]:
"""
Returns the first credentials from pgpass that contain all the values
passed in.
Supported Parameters:
host, port, dbname, user, password
>>> from tempfile import mkstemp
>>> _, path = mkstemp()
>>> f = open(path, 'w')
>>> _ = f.write("myhost:myport:mydbname:myname:mypass\\n")
>>> _ = f.write("byhost:byport:bydbname:byname:bypass")
>>> f.close()
>>> assert(find_credentials(path, user='myname')['password'] == 'mypass')
>>> assert(find_credentials(path, dbname='bydbname')['user'] == 'byname')
>>> assert(find_credentials(path, host='not-host'))
Traceback (most recent call last):
...
Exception: No such credentials available.
"""
creds = get_credentials(credentials_file)
for key, value in kwargs.items():
if value:
creds = list(filter(lambda x: x.get(key) == value, creds))
if len(creds) == 0:
raise Exception('No such credentials available.')
return creds[0]
def get_cursor(credentials_file='~/.pgpass', **kwargs):
c = find_credentials(credentials_file, **kwargs)
return SingleCursorDatabaseConnector(c['dbname'], c['host'], c['port'],
c['user'], c['password'])
def query(q: str, credentials_file='.pgpass'):
'''
Execute a query in redshift/postgres.
Parameters
----------
q : str
psql query string
Returns
-------
query results
'''
with get_cursor(credentials_file=credentials_file) as cur:
# execute
cur.execute(q)
# fetch results
try:
res = cur.fetchall()
# get result column names
cols = [c.name for c in cur.description]
except Exception as e:
log.warn("Could not fetch results for query: " + q)
raise e
return (res, cols)
class SingleCursorDatabaseConnector(object):
"""
Wraps the psycopg2 connection and cursor functions to reconnect on close.
SingleCursorDatabaseConnector maintains a single cursor to a psycopg2
database connection. Lazy initialization is used, so all connection and
cursor management happens on the method calls.
"""
def __init__(self,
database,
host='localhost',
port=5439,
user='postgres',
password='postgres',
autocommit=True):
"""
Lazy constructor for the class.
Parameters
----------
database : str
The name of the database to connect to
host : str
Host name of the server the database is running on
port : int
Port the database is running on
user : str
Username to connect as
password : str
Password for the connection
autocommit : bool
If True, then no transaction is left open. All commands have
immediate effect.
"""
self.database = database
self.host = host
self.port = port
self.user = user
self.password = password
self.autocommit = autocommit
self._cursor = None
self._connection = None
def _connect(self):
self._connection = psycopg2.connect(database=self.database,
host=self.host,
port=self.port,
user=self.user,
password=self.password)
self._connection.autocommit = self.autocommit
return self._connection
def _get_connection(self):
if self._connection and not self._connection.closed:
return self._connection
self._cursor = None
return self._connect()
def _get_cursor(self):
if self._cursor and not self._cursor.closed:
return self._cursor
self._cursor = self._get_connection().cursor()
return self._cursor
def execute(self, *args, **kwargs):
return self._get_cursor().execute(*args, **kwargs)
def fetchone(self):
return self._get_cursor().fetchone()
def fetchmany(self, *args, **kwargs):
return self._get_cursor().fetchmany(*args, **kwargs)
def fetchall(self):
return self._get_cursor().fetchall()
def __getattr__(self, name):
return getattr(self._get_cursor(), name)
def __iter__(self):
return self._get_cursor()
@property
def statusmessage(self):
cursor = self._get_cursor()
if cursor:
return cursor.statusmessage
else:
return None
def commit(self):
self._get_connection().commit()
def rollback(self):
self._get_connection().rollback()
def close(self):
self._get_connection().close()
PK ! = cranial/datastore/dbapi.pyimport importlib
class Param:
def __init__(self, value):
self.value = value
def __repr__(self):
return 'Param(%r)' % (self.value,)
def to_qmark(chunks):
query_parts = []
params = []
for chunk in chunks:
if isinstance(chunk, Param):
params.append(chunk.value)
query_parts.append('?')
else:
query_parts.append(chunk)
return ''.join(query_parts), params
def to_numeric(chunks):
query_parts = []
params = []
for chunk in chunks:
if isinstance(chunk, Param):
params.append(chunk.value)
query_parts.append(':%d' % len(params))
else:
query_parts.append(chunk)
return ''.join(query_parts), tuple(params) # DCOracle2 has broken support
# for sequences of other types
def to_named(chunks):
query_parts = []
params = {}
for chunk in chunks:
if isinstance(chunk, Param):
name = 'p%d' % len(params) # Are numbers in name allowed?
params[name] = chunk.value
query_parts.append(':%s' % name)
else:
query_parts.append(chunk)
return ''.join(query_parts), params
def to_format(chunks):
query_parts = []
params = []
for chunk in chunks:
if isinstance(chunk, Param):
params.append(chunk.value)
query_parts.append('%s')
else:
query_parts.append(chunk.replace('%', '%%'))
return ''.join(query_parts), params
def to_pyformat(chunks):
query_parts = []
params = {}
for chunk in chunks:
if isinstance(chunk, Param):
name = '%d' % len(params)
params[name] = chunk.value
query_parts.append('%%(%s)s' % name)
else:
query_parts.append(chunk.replace('%', '%%'))
return ''.join(query_parts), params
def get_paramstyle(conn):
""" This should work with a connection or cursor object."""
name = conn.__class__.__module__.split('.')[0]
mod = importlib.import_module(name)
return mod.paramstyle
def render_params(conn, chunks):
try:
style = get_paramstyle(conn)
except:
style = 'format'
return globals()['to_' + style](chunks)
def get_temp_db(filename=None):
import sqlite3
if filename is None:
conn = sqlite3.connect(":memory:")
else:
conn = sqlite3.connect(filename)
return conn.cursor()
PK ! p p cranial/fetcher.py"""
A Fetcher is a the combination of a Connector and a Parser, providing a
standard way to retrieve data records as Dictionaries from arbitrary storage
systems, via a generator.
"""
from cranial.connectors.base import Connector
from cranial.parsers import base, line
class Parser():
pass
class Fetcher():
def __init__(self, connector: Connector, parser: base.Parser=line.Parser) -> None:
self.connector = connector
self.parser = parser
def __iter__(self):
return self.generator()
def generator(self):
for record in self.parser(self.connector):
yield record
PK ! In n cranial/fetchers.py# Backward compatibility.
from cranial.connectors import *
# Convenience
from cranial.fetcher import Fetcher
PK ! Ý cranial/keyvalue/README.rstKeyValueDB is intended to allow external databases to be used as a drop-in
replacement for Python Dictionaries in many use cases. Once you've initialized
a KeyValueDB object, if you know how to use a Dict, then you know how to use
it. Choosing the right sub-class and parameter options for maximum performance
for your application does require some understanding of the internals, however.
KeyValueDB is intended for rapid prototyping and optimized for ease-of-use, not
performance. Expect to need to do some refactoring, probably with a custom
sub-class, to make an application production-ready.
The first argument to a KeyValueDB init can be any DBAPI2-compatible cursor.
Since the Cassanda driver is not DBAPI2-compatible, we provide the
CassandraAdapter class which wrapps a Cassanda session and provides the DBAPI2
interface. Other database adapters in cranial are provided for convenience, and
are not necessary for use with KeyValueDB, though they may make it easier to
get a reliable cursor.
KeyValueDB does not depend on fetchers. They are mostly separate tools for
separate jobs at the present. In the future, it is conceivable that a fetcher
could make use of an optimized KeyValueDB subclass. But because fetchers are
not DBAPI2 compatible (because they are intended to support data storage
systems more generally, and not just databases), it is unlikely one would ever
want to use a fetcher inside a KeyValueDB subclass.
PK ! ړO cranial/keyvalue/__init__.pyfrom .keyvalue import *
PK ! ]0ޘ cranial/keyvalue/interceptor.pyfrom cranial.keyvalue import keyvalue
class DeleteOp:
"""This class is passed as the 'value' to the intercept function for a
__delitem__ operation. This allows the intercept function to differentiate
a Delete from a Get."""
pass
class GetOp:
""" @see DeleteOp."""
pass
class KeyValueInterceptor(keyvalue.KeyValueDB):
''' Adds to KeyValueDB the ability provide a "interceptor" function that can
make modifications based on the key.
>>> import pickle
>>> kv = get_mock()
>>> def fn(obj, key, value=None):
... obj.valcol = 'alt' if key == 'bar' else 'value'
... return key, value
...
>>> kv.set_interceptor(fn)
>>> kv['foo'] = 'a'
>>> kv['foo']
'a'
>>> kv['bar'] = 'b'
>>> kv['bar']
'b'
>>> list(map(lambda x: (x[0], pickle.loads(x[1]) if x[1] else x[1], pickle.loads(x[2]) if x[2] else x[2]), kv.db.execute("SELECT * FROM test").fetchall()))
[('foo', 'a', None), ('bar', None, 'b')]
>>> del(kv['foo'])
>>> kv.db.connection.close()
'''
def set_interceptor(self, fn: callable):
""" fn(self, key, value) -> key, value"""
if hasattr(self, 'intercept'):
raise Exception("Intercept function should only be set once.")
else:
self.intercept = fn
def __getitem__(self, key):
if hasattr(self, 'intercept'):
key, _ = self.intercept(self, key, GetOp)
return super().__getitem__(key)
def __setitem__(self, key, value):
if hasattr(self, 'intercept'):
key, value = self.intercept(self, key, value)
return super().__setitem__(key, value)
def __delitem__(self, key):
if hasattr(self, 'intercept'):
key, _ = self.intercept(self, key, DeleteOp)
return super().__delitem__(key)
""" Module Functions. """
def get_mock():
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"CREATE TABLE test (key VARCHAR, value BLOB, alt BLOB);"
).connection.commit()
return KeyValueInterceptor(cur, 'test', commit_fn=conn.commit)
if __name__ == "__main__":
import doctest
doctest.testmod()
PK ! *,bpx px cranial/keyvalue/keyvalue.pyimport pickle
import json
from typing import Iterable
from cachetools import TTLCache
from cranial.common import logger
from cranial.datastore.dbapi import get_temp_db
log = logger.get(name='cranial.keyvalue')
# Default Databse Column type for values when blob is False
DEFAULT_TYPE = 'text'
class KeyValueDB(object):
'''This object should mostly work like a dictionary, except it reads and
writes from an external database. Subclasses can implement caching as
appropriate.
This class assumes that the database enforces uniqueness of the keys. I.e.,
all SELECT queries will have LIMIT 1.
>>> kv = get_mock()
>>> kv['foo'] = 'a'
>>> kv[1] = 'int'
>>> kv.cache_clear()
>>> kv['foo']
'a'
>>> kv[1]
'int'
>>> kv['bar'] = 'b'
>>> kv.cache_clear()
>>> kv['bar']
'b'
>>> kv['foo'] = 'c'
>>> kv.cache_clear()
>>> kv['foo'] = 'd'
>>> kv.cache_clear()
>>> kv['foo']
'd'
>>> kv['bar']
'b'
>>> kv.db.connection.close()
'''
def __init__(self, cursor,
table: str,
create_table: bool = False,
truncate_table: bool = False,
drop_table: bool = False,
keycol: str = 'key',
valcol: str = 'value',
blob=True,
keytype: str = 'text',
valtype: str = DEFAULT_TYPE, # Default if `blob` is False.
placeholder: str = '?',
commit_fn: callable = None,
cachesize=2 ** 10,
cacheduration=3600):
"""Create a KeyValueDB object with given connection and table.
By default, the value type is pickled blob. Users can pass `blob=False`
to serialize data as JSON in a text field, or `valtype='TYPE'` where
TYPE is any type supported by the database.
Parameters
----------
cursor
A DBAPI2 cursor, or at least an object with an .execute()
method that accepts SQL query and a .fetchone() method that
returns a row.
table
A table with 'key' and 'value' columns in the connected DB.
create_table
If True, execute 'create table if not exists ...'
keycol
Column name for key values, default 'key'
valcol
Column name for value values, default 'value'
keytype
If create_table, the datatype for the key. Default 'text'.
valtype
If create_table, the datatype for the value. Default 'blob' when
`blob` parameter (below) is true, otherwise, 'text.'
blob **DEPRECATED**
If True, use pickle to (de)serialize, if False, use json. To support
this, the cursor.execute() method must be able to accept a `bytes`
parameter.
placeholder
The placeholder character required by the cursor's `paramstyle`.
Defaults to '?'.
commit_fn
An optional function that will be called after writes with
no arguments. If using a transactional DBAPI2 cursor without
autocommit, this should probably be cursor.connection.commit
unless you are handling transactions elsewhere.
cachesize
Max size for the LRU cache.
cacheduration
Seconds after which cache items will be expired.
"""
self.db = cursor
self.table = table
self.keycol = keycol
self.keytype = keytype
self.valcol = valcol
self.valtype = 'blob' if blob and valtype is DEFAULT_TYPE else valtype
self.placeholder = placeholder
self.commit = commit_fn
self.cache = TTLCache(maxsize=cachesize, ttl=cacheduration)
if create_table:
self._create_table(drop_table)
elif truncate_table:
self.db.execute("TRUNCATE {};".format(table))
self._get_table_columns()
def _get_table_columns(self):
"""
Not ideal way to look up what columns are there in the underlying table
# @TODO: make this less dependent on database type
"""
try:
# Better for Cassandra/Scylla.
self.db.execute("SELECT column_name FROM system_schema.columns "
"WHERE keyspace_name = 'default' and table_name = '{}'".format(self.table))
self.table_columns = [r.column_name for r in self.db.fetchall()]
except:
log.info("Couldn't get columns through system_schema.")
try:
# For DBAPI2 databases.
self.db.execute("SELECT * FROM {} LIMIT 1".format(self.table))
self.table_columns = [d[0] for d in self.db.description]
except:
log.warning("Couldn't get columns through row.")
if not self.table_columns:
raise Exception("Could not initialize table_columns. Maybe table does not exist.")
else:
log.info("{} table has these columns: {}".format(self.table, self.table_columns))
return self.table_columns
def _create_table(self, drop_table):
"""
helper method to run 'create table' query,
optionally drop the table if it exists before creating it again
Parameters
----------
drop_table
if True, try dropping table before creating
"""
if drop_table:
log.warning("Dropping table if exists: {}".format(self.table))
self.db.execute(
"DROP TABLE IF EXISTS {t} ".format(t=self.table))
self.db.execute(
"""CREATE TABLE IF NOT EXISTS {t} (
{k} {ktype} PRIMARY KEY,
{v} {vtype});""".format(t=self.table,
k=self.keycol,
ktype=self.keytype,
v=self.valcol,
vtype=self.valtype))
def _to_blob(self, v):
return pickle.dumps(v, protocol=4) \
if self.valtype is 'blob' else json.dumps(v)
def __getitem__(self, key):
"""
Basic get/set is tested throughout the class. Here we test the cache.
>>> kv = get_mock()
>>> kv['witch'] = 'duck'
>>> 'witch' in kv.cache
True
"""
if not (key in self.cache):
base_query = "SELECT {} from {} where {} = {} LIMIT 1".format(
self.valcol, self.table, self.keycol, self.placeholder)
self.db.execute(base_query, [key])
result = self.db.fetchone()[0]
unserialized = pickle.loads(result) \
if self.valtype is 'blob' else json.loads(result)
self.cache[key] = unserialized
return self.cache[key]
def get(self, key, default=None):
"""
analog of dict.get
Parameters
----------
key
key
default
if key is not found, return this value, default is None
Returns
-------
value corresponding to the key, or default
"""
try:
result = self[key]
if result is None:
return default
except KeyError as e:
log.debug(str(e))
return default
except Exception as e:
log.warning(str(e))
return default
return result
def __setitem__(self, key, value):
serialized_value = self._to_blob(value)
# Subjectively, UPDATE||INSERT is faster than DEL+INSERT in Redshift.
# This could possibly be optimized for Cassandra, it works fine.
try:
base_query = "UPDATE {} SET {} = {} WHERE {} = {}".format(
self.table, self.valcol, self.placeholder, self.keycol,
self.placeholder)
self.db.execute(base_query, [serialized_value, key])
if key in self.cache:
del (self.cache[key])
if self.db.rowcount < 1:
base_query = "INSERT INTO {} ({}, {}) VALUES ({}, {})".format(
self.table, self.keycol, self.valcol,
self.placeholder, self.placeholder)
self.db.execute(base_query, [key, serialized_value])
self.cache[key] = value
if self.commit:
self.commit()
return value
except Exception as e:
log.error('{}: {}'.format(type(e), e))
log.error("Could not update {} => {}".format(key, value))
def __delitem__(self, key):
base_query = "DELETE from {} where {} = {}".format(
self.table, self.keycol, self.placeholder)
self.db.execute(base_query, [key])
if key in self.cache:
del (self.cache[key])
if self.commit:
self.commit()
return key
def __missing__(self, key):
raise KeyError('No such key.')
def cache_clear(self):
"""
>>> kv = get_mock()
>>> kv['witch'] = 'duck'
>>> kv.cache_clear()
>>> 'witch' in kv.cache
False
"""
self.cache = TTLCache(self.cache.maxsize, self.cache.ttl)
def keys(self):
self.db.execute("SELECT distinct {} from {}".format(
self.keycol, self.table))
for r in self.db.fetchall():
yield r[0]
def __len__(self):
return self.db.execute("SELECT COUNT(1) from {}".format(
self.table)).fetchone()[0]
class KeyValueReadOnly(KeyValueDB):
"""Access a Key-Value table with protection against writes.
>>> kv = get_mock()
>>> kv['foo'] = 'a'
>>> kv[1] = 'int'
>>> kv.cache_clear()
>>> kv['foo']
'a'
>>> ro = KeyValueReadOnly(kv.db, kv.table, blob=False)
>>> ro['foo']
'a'
>>> ro['foo'] = 'b'
Traceback (most recent call last):
File "keyvalue.py", line 000, in __setitem__
raise Exception('Read-only data.')
Exception: Read-only data.
>>> del(ro['foo'])
Traceback (most recent call last):
File "keyvalue.py", line 000, in __delitem__
raise Exception('Read-only data.')
Exception: Read-only data.
"""
def __init__(self, cursor, table: str,
keycol: str = 'key', valcol: str = 'value', blob=True,
keytype: str = 'text', valtype: str = DEFAULT_TYPE,
placeholder: str = '?'):
super().__init__(cursor=cursor,
table=table,
keycol=keycol,
valcol=valcol,
blob=blob,
keytype=keytype,
valtype=valtype,
placeholder=placeholder)
def __setitem__(self, key, value):
raise Exception('Read-only data.')
def __delitem__(self, key):
raise Exception('Read-only data.')
""" Module Functions. """
class StringSerDe():
def dumps(self, v):
return str(v)
def loads(self, v):
# Return None as-is to indicate a Null column.
return str(v) if v is not None else v
class BoolIntSerDe():
def dumps(self, v):
if v is True:
return 1
elif v is False:
return 0
else:
return v
def loads(self, v):
if v is 1:
return True
elif v is 0:
return False
else:
return v
class NoOpSerDe():
def dumps(self, v):
return v
def loads(self, v):
return v
class KeyRowDB(KeyValueDB):
""" This should work well for Cassandra/Scylla, and OK on traditional
Relational DBs with an index on the key. You Probably don't want to use this
on Redshift, though performance should be acceptable if the key is your
table's SORTKEY.
Tests to demostrate interoperability with KeyValueDB class:
>>> kv = get_mock()
>>> kr = KeyRowDB(kv.db, kv.table)
>>> kv['foo'] = 'a'
>>> kr['foo']['value'] == 'a' and kr['foo']['other'] == None
True
>>> kr['foo'] = {'other': 'x', 'value': 'b'}
>>> kv.cache_clear()
>>> kv['foo']
'b'
>>> kr['foo'] = {'key': 'foo', 'other': 'x', 'value': 'b'}
>>> kv['foo'] = 'c'
>>> kr.cache_clear()
>>> kr['foo']['value'] == 'c' and kr['foo']['other'] == 'x'
True
"""
def __init__(self, cursor,
table: str,
valcols: Iterable = None,
create_table: bool = False,
truncate_table: bool = False,
drop_table: bool = False,
keycol: str = 'key',
keytype: str = DEFAULT_TYPE,
valtype: str = DEFAULT_TYPE,
placeholder: str = '?',
commit_fn: callable = None,
blob=False,
serde: 'loads/dumps' = json,
cachesize=2 ** 10,
cacheduration=3600):
"""
If table creation is desired, the user must provide valcols. By default,
values will be stored in text columns as json. Alternatively, the user
may set either `blob = True` to store pickled bytes, or set `serde` to
an object that will convert values to/from strings.
>>> cur = get_temp_db()
>>> cur.execute("CREATE TABLE simple (key VARCHAR, knights VARCHAR)"
... ).connection.commit()
>>> simple = KeyRowDB(cur, 'simple')
>>> simple['spam'] = {'knights': 'ni!'}
>>> cur.execute("SELECT * FROM simple").fetchone()
('spam', '"ni!"')
>>> dropped = KeyRowDB(cur, 'simple', valcols=['different'],
... drop_table=True, create_table=True)
>>> cur.execute("SELECT * FROM simple").fetchone() is None
True
>>> created = KeyRowDB(cur, 'created', valcols=['spam'],
... create_table=True)
>>> created['camelot'] = {'spam': 'alot'}
>>> pickled = KeyRowDB(cur, 'pickled', valcols=['v'],
... create_table=True, blob=True)
>>> pickled['grenade'] = {'v': {'count': 5}}
>>> pickled.cache_clear()
>>> pickled['grenade']['v']['count'] is 5
True
>>> numeric = KeyRowDB(cur, 'numeric', keycol='num', keytype='int',
... valcols= ['word'], create_table=True)
>>> numeric[1] = {'word': 'foo'}
>>> cur.execute("SELECT * FROM numeric").fetchone()
(1, '"foo"')
"""
assert callable(serde.loads)
assert callable(serde.dumps)
self.valcols = valcols
super().__init__(cursor=cursor,
table=table,
keycol=keycol,
keytype=keytype,
valtype=valtype,
placeholder=placeholder,
blob=blob,
create_table=create_table,
truncate_table=truncate_table,
drop_table=drop_table,
commit_fn=commit_fn,
cachesize=cachesize,
cacheduration=cacheduration)
del self.valcol
if not create_table:
existing_cols = set(self.table_columns)
if self.valcols is not None:
req_cols = set(self.valcols)
assert all([c in existing_cols for c in req_cols]), \
"these columns do not exist in the already existing table: {}".format(req_cols - existing_cols)
self.serde = pickle if self.valtype is 'blob' else serde
def _check_coltypes(self, cols, coltype):
"""
make sure that coltype is a dict where keys are column names and values are their data types
Parameters
----------
cols
list of column names
coltype
- if dict, make sure all columns are in dict keys and fill with default data type if missing
- if iterable, has to have the same number of items as column names,
the two lists will be zipped together
- if str, this type will be used for all columns
Returns
-------
dict with {column:datatype}
"""
if isinstance(coltype, dict):
coltype = {c: coltype.get(c, DEFAULT_TYPE) for c in cols}
elif isinstance(coltype, (list, tuple)):
assert len(cols) == len(coltype), "when column types are given as list the " \
"number should match the number of columns"
coltype = dict(zip(cols, coltype))
elif isinstance(coltype, str):
coltype = {c: coltype for c in cols}
else:
raise Exception("column types should be either dict, list, tuple or string")
return coltype
def _create_table(self, drop_table):
"""
>>> cur = get_temp_db()
>>> serde = StringSerDe()
>>> kr = KeyRowDB(cur, 'newtable', commit_fn=cur.connection.commit,
... create_table = True,
... valcols=['foo', 'bar' , 'baz'], serde=serde)
>>> kr['spam'] = {'foo': 'a', 'bar': 'b'}
>>> kr.cache_clear()
>>> kr['spam'] == {'foo': 'a', 'bar': 'b', 'baz': None}
True
"""
if not self.valcols:
raise Exception("Can't create table without defined columns.")
if drop_table:
log.warning("Dropping table if exists {}".format(self.table))
self.db.execute(
"DROP TABLE IF EXISTS {t} ".format(t=self.table))
query = self._create_table_query()
self.db.execute(query)
log.info("Created table {} (if it didn't exist already)".format(
self.table))
def _create_table_query(self):
"""
Factor out query definition and its execution from _create_table method
"""
# make sure column types are set for every column
self.valtype = self._check_coltypes(self.valcols, self.valtype)
# Initialize columns with Key. Then append Additional columns.
columns = ['{} {} PRIMARY KEY'.format(self.keycol, self.keytype)]
columns += ['{} {}'.format(name, dtype)
for name, dtype in self.valtype.items()]
query = "CREATE TABLE IF NOT EXISTS {table} ({columns});".format(
table=self.table, columns=','.join(columns))
return query
def _execute_get_query(self, key):
"""
Factor out the query definition and its execution from __getitem__.
"""
# @TODO Update to support varying Column Types.
base_query = "SELECT {} from {} where {} = {} LIMIT 1".format(
'*' if not self.valcols else ','.join(self.valcols),
self.table,
self.keycol,
self.placeholder)
log.debug(base_query)
self.db.execute(base_query, [key])
def get(self, key, default=None):
"""
Parameters
----------
key
default
1. Can be a dict, with valcols as keys and values as default values
for each column.
2. Can be a list with the same number of values as the number of
valcols, list items correspond
to individual default values for each of the valcols.
3. Can be anything else, in this case the same default value will
be used for all columns.
If there is a need to use default value of dict or list type for
all columns - replicate the value and use option 1 or 2.
Returns
-------
"""
if default is not None:
for k in default:
assert k in (self.valcols or self.table_columns)
return super().get(key, default)
def __getitem__(self, key):
"""
Basic get/set is tested throughout the class. Here we test the cache.
>>> cur = get_temp_db()
>>> kr = KeyRowDB(cur, 'simple', valcols=['weight'], create_table=True)
>>> kr['witch'] = {'weight': 'duck'}
>>> 'witch' in kr.cache
True
"""
if not (key in self.cache):
self._execute_get_query(key)
columns = self.valcols or self.table_columns
result = self.db.fetchone()
if not result:
raise KeyError("key {} is not found".format(key))
# Pair values with column name.
values_zip = zip(columns, result)
# Deserialize.
values = {}
for k, v in values_zip:
try:
v = self.serde.loads(v)
except Exception as e:
# The Key column usually isn't serialized.
if v is not None and k != self.keycol:
log.warning('Exception for key {}: {}'.format(k, v))
log.warning(e)
# If Deserializing failed, fall-through to using the column
# data as-is.
values[k] = v
self.cache[key] = values
return self.cache[key]
def __setitem__(self, key, values: dict):
assert type(values) is dict
# make sure there is no keycol in values dict
values.pop(self.keycol, None)
data = [[f, self.serde.dumps(v)] for f, v in values.items()]
try:
values_str = ', '.join(
['{} = {}'.format(f, self.placeholder) for f, v in data])
base_query = "UPDATE {} SET {}".format(self.table, values_str)
base_query += " WHERE {} = {}".format(self.keycol, self.placeholder)
log.debug(base_query)
self.db.execute(base_query, [v for f, v in data] + [key])
if self.db.rowcount < 1:
data.append([self.keycol, key])
base_query = "INSERT INTO {} ({}) VALUES ({})".format(
self.table,
', '.join([f for f, v in data]),
', '.join([self.placeholder for _ in data]))
log.debug(base_query)
self.db.execute(base_query, [v for f, v in data])
self.cache[key] = values
if self.commit:
self.commit()
return values
except Exception as e:
log.error('{}: {}'.format(type(e), e))
log.error("Could not update {} => {}".format(key, values))
class CompoundKeyRowDB(KeyRowDB):
""" This CompoundKeyRowDB object takes tuples as keys.
@TODO It might be an improvement to eliminate this class and simply have
the code here used in KeyRowDB when KeyRowDB.keycol is a tuple.
"""
def __init__(self, cursor,
table: str,
keycols: Iterable = None,
valcols: Iterable = None,
create_table: bool = False,
truncate_table: bool = False,
drop_table: bool = False,
keytype = DEFAULT_TYPE,
valtype = DEFAULT_TYPE,
placeholder: str = '?',
commit_fn: callable = None,
blob=False,
# @TODO Define Serde Abstract Base Class.
serde: 'loads/dumps' = json,
cachesize=2 ** 10,
cacheduration=3600):
"""
If table creation is desired, the user must provide valcols. By default,
values will be stored in text columns as json. Alternatively, the user
may set either `blob = True` to store pickled bytes, or set `serde` to
an object that will convert values to/from strings.
>>> cur = get_temp_db()
>>> cur.execute("CREATE TABLE simple (a VARCHAR, b VARCHAR, c VARCHAR, d VARCHAR)"
... ).connection.commit()
>>> simple = CompoundKeyRowDB(cur, 'simple', keycols=['a', 'b'])
>>> simple[('foo', 'bar')] = {'c': 'knights', 'd': 'ni!'}
>>> cur.execute("SELECT * FROM simple").fetchone()
('foo', 'bar', '"knights"', '"ni!"')
>>> dropped = CompoundKeyRowDB(cur, 'simple', keycols=['a', 'b'], valcols=['different'],
... drop_table=True, create_table=True)
>>> cur.execute("SELECT * FROM simple").fetchone() is None
True
>>> created = CompoundKeyRowDB(cur, 'created', keycols=['a', 'b'], valcols=['spam'],
... create_table=True)
>>> created[('cam', 'elot')] = {'spam': 'alot'}
>>> pickled = CompoundKeyRowDB(cur, 'pickled', keycols=['a', 'b', 'c'], valcols=['v'],
... create_table=True, blob=True)
>>> pickled[('gre', 'n', 'ade')] = {'v': {'count': 5}}
>>> pickled.cache_clear()
>>> pickled[('gre', 'n', 'ade')]['v']['count'] is 5
True
>>> numeric = CompoundKeyRowDB(cur, 'numeric', keycols=['a', 'b'], keytype='int',
... valcols=['word', 'num'], valtype=['text', 'decimal'], create_table=True)
>>> numeric[(1, 2)] = {'word': 'foo', 'num': 3.14}
>>> cur.execute("SELECT a, b, word, num FROM numeric").fetchone()
(1, 2, '"foo"', 3.14)
"""
assert callable(serde.loads)
assert callable(serde.dumps)
self.keycols = keycols
super().__init__(cursor=cursor,
table=table,
valcols=valcols,
keytype=keytype,
valtype=valtype,
placeholder=placeholder,
blob=blob,
create_table=create_table,
truncate_table=truncate_table,
drop_table=drop_table,
commit_fn=commit_fn,
cachesize=cachesize,
cacheduration=cacheduration)
del self.keycol
def keys(self):
raise NotImplementedError("This class does not have method 'keys'")
def _create_table_query(self):
"""
Different way to define columns and set compound primary key.
This is used inside _create_table method
>>> cur = get_temp_db()
>>> serde = StringSerDe()
>>> kr = CompoundKeyRowDB(cur, 'newtable', commit_fn=cur.connection.commit,
... create_table = True, keycols=['a', 'b'],
... valcols=['foo', 'bar' , 'baz'], serde=serde)
>>> kr[('spam', 'alot')] = {'foo': 'a', 'bar': 'b'}
>>> kr.cache_clear()
>>> kr[('spam', 'alot')] == {'foo': 'a', 'bar': 'b', 'baz': None}
True
"""
# make sure column types are set for every column
self.valtype = self._check_coltypes(self.valcols, self.valtype)
self.keytype = self._check_coltypes(self.keycols, self.keytype)
log.debug(self.valtype)
log.debug(self.keytype)
columns = []
columns += ['{} {}'.format(name, dtype) for name, dtype in self.keytype.items()]
columns += ['{} {}'.format(name, dtype) for name, dtype in self.valtype.items()]
query = "CREATE TABLE IF NOT EXISTS {table} ({columns}, PRIMARY KEY ({key_cols}))".format(
table=self.table, columns=','.join(columns), key_cols=','.join(self.keycols))
return query
def _execute_get_query(self, key):
"""
Different select query to filter on multiple column.
This is used inside __getitem__ method
"""
# @TODO Update to support varying Column Types.
base_query = "SELECT {} from {} where {} LIMIT 1".format(
'*' if not self.valcols else ','.join(self.valcols),
self.table,
" AND ".join(["{} = {}".format(c, self.placeholder) for c in self.keycols])
)
log.debug(base_query)
self.db.execute(base_query, key)
def __setitem__(self, key, values: dict):
"""
To adapt to the fact that key is a tuple:
- different way to make sure there is no keycol in values dict
- different UPDATE query and exec
- different INSERT query and exec
"""
assert type(values) is dict
# make sure there is no keycol in values dict
_ = [values.pop(c, None) for c in self.keycols]
data = [[f, self.serde.dumps(v)] for f, v in values.items()]
try:
values_str = ', '.join(
['{} = {}'.format(f, self.placeholder) for f, v in data])
base_query = "UPDATE {} SET {}".format(self.table, values_str)
base_query += " WHERE " + " AND ".join(["{} = {}".format(c, self.placeholder) for c in self.keycols])
log.debug(base_query)
self.db.execute(base_query, [v for f, v in data] + list(key))
if self.db.rowcount < 1:
data.extend(zip(self.keycols, key))
base_query = "INSERT INTO {} ({}) VALUES ({})".format(
self.table,
', '.join([f for f, v in data]),
', '.join([self.placeholder for _ in data]))
log.debug(base_query)
self.db.execute(base_query, [v for f, v in data])
self.cache[key] = values
if self.commit:
self.commit()
return values
except Exception as e:
log.error('{}: {}'.format(type(e), e))
log.error("Could not update {} => {}".format(key, values))
def __delitem__(self, key):
"""
Override to adopt query for mylti-column key
"""
base_query = "DELETE from {}".format(self.table)
base_query += " WHERE " + " AND ".join(["{} = {}".format(c, self.placeholder) for c in self.keycols])
log.debug(base_query)
self.db.execute(base_query, key)
if key in self.cache:
del (self.cache[key])
if self.commit:
self.commit()
return key
class StringKeyRowDB(KeyRowDB):
"""Forces keys to be strings. Mainly for SQLite & testing."""
def __getitem__(self, key):
return super().__getitem__(str(key))
def __setitem__(self, key, values):
return super().__setitem__(str(key), values)
def __delitem__(self, key):
return super().__delitem__(str(key))
class UncountableKeyRowDB(KeyRowDB):
def __len__(self):
return 1
def get_mock(name='test', filename=None):
cur = get_temp_db(filename)
cur.execute(
"CREATE TABLE {} (key VARCHAR, value VARCHAR, other VARCHAR);".format(
name)).connection.commit()
return KeyValueDB(cur, name, blob=False, commit_fn=cur.connection.commit)
if __name__ == "__main__":
import doctest
doctest.testmod()
PK ! cranial/keyvalue/kvandra.py'''
Helper functions to work with Cassandra via KeyValueDB.
'''
import json
import os
from cassandra.cluster import Cluster
from cassandra.policies import TokenAwarePolicy, RoundRobinPolicy
from cassandra.query import named_tuple_factory
from cassandra.auth import PlainTextAuthProvider
from cranial.datastore.adapters.cassandra import CassandraAdapter as Adapter
from cranial.keyvalue.keyvalue import KeyValueDB as KeyValue
from cranial.common import logger
log = logger.get()
session = None
def get_cursor(existing=None, hosts=None, new=False):
global session
if existing:
return existing
if session and not new:
return session
if hosts is None:
hosts = os.environ.get('KEYVALUE_HOSTS', '').split(',')
auth = None
try:
with open('keys/cassandra-config.json') as f:
auth = PlainTextAuthProvider(**json.load(f))
except Exception as e:
log.warning('Could not get Cassandra credentials from file.')
log.warning(e)
cluster = Cluster(
hosts,
load_balancing_policy=TokenAwarePolicy(RoundRobinPolicy()),
auth_provider=auth)
session = cluster.connect('default')
session.row_factory = named_tuple_factory
return session
def get_kv(name, **kwargs):
return KeyValue(Adapter(get_cursor()),
table=name,
create_table=True,
**kwargs)
PK ! |wfK K ) cranial_datastore-0.3.3.dist-info/LICENSE GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
PK !HW"T T ' cranial_datastore-0.3.3.dist-info/WHEEL
A
н#J."jm)Afb~
ڡ5G7hiޅF4+-3ڦ/̖?XPK !H Ob * cranial_datastore-0.3.3.dist-info/METADATAMO1+T:TTRQQPqFJ+]'k1l
dzk;Ge_ ,L>tRe@#E3,MZۡ^%G\9kZΊ$nQ
v@_e+";ǂ_TrDŴy͔5]lf(`˴j:
d}v2:jS?3ҿg#ɸtƷp+/^\}/jHoc^lёrqoPK !H ( cranial_datastore-0.3.3.dist-info/RECORDɒH}BqJA@`C $ %2>}ۋK6:*d3mTQWe j0˼÷z,"i/gR*
Q6!;JZ$#YW_up%4Vq74B6<~L2&q cIrHTUqQ
Iul'wҸ3W&}'FF
^9zE67~>6C1è)ȤJTlCYTqTLsIjl+zQ&I~j5LA4]kJ1g _X=BOİ$姴)ڒb;hKR$ߣ${2iﻔ=A*Z_j}h,Frz(@EYBJeȦi;NMvvF>nweFArzLK \:_5`ߤgW_vMkhykLEeo2}v) q)R9nr P6m?edX@ZӣSV#˷+pAZŘb冰&p6⛺e[ j[_$2`~됊}7Zȝyuvx(6_psS|f%G;s?fX,鳦Ջɼ|95+' y"742Rb-#{gO.Q'$:P^;@9@QC?lˠB) 5f
ax:9hmx2C\P?Rz؞cY=?{Ϣ̗~$N]eZNW§ѫpل-iΏrɀtoL
bq%I
ɮ?2mMڦe4}|hy\d`_M4r.%'Oxrp(2k.`YΰD7PK ! G cranial/connectors/__init__.pyPK ! +) N cranial/connectors/base.pyPK ! ? (
cranial/connectors/googlecloudstorage.pyPK ! Ȝz R cranial/connectors/http.pyPK ! $.
'$ cranial/connectors/local.pyPK ! HM M g1 cranial/connectors/s3.pyPK ! X@ ' M cranial/datastore/adapters/cassandra.pyPK ! x x " W cranial/datastore/adapters/psql.pyPK ! = |s cranial/datastore/dbapi.pyPK ! p p c} cranial/fetcher.pyPK ! In n cranial/fetchers.pyPK ! Ý cranial/keyvalue/README.rstPK ! ړO x cranial/keyvalue/__init__.pyPK ! ]0ޘ ʆ cranial/keyvalue/interceptor.pyPK ! *,bpx px cranial/keyvalue/keyvalue.pyPK ! I cranial/keyvalue/kvandra.pyPK ! |wfK K ) cranial_datastore-0.3.3.dist-info/LICENSEPK !HW"T T ' cranial_datastore-0.3.3.dist-info/WHEELPK !H Ob * ? cranial_datastore-0.3.3.dist-info/METADATAPK !H ( cranial_datastore-0.3.3.dist-info/RECORDPK