signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def delete_file(self, project_name, remote_path):
|
project = self._get_or_create_project(project_name)<EOL>remote_file = project.get_child_for_path(remote_path)<EOL>remote_file.delete()<EOL>
|
Delete a file or folder from a project
:param project_name: str: name of the project containing a file we will delete
:param remote_path: str: remote path specifying file to delete
|
f3939:c1:m12
|
def replace_invalid_path_chars(path):
|
for bad_char in INVALID_PATH_CHARS:<EOL><INDENT>path = path.replace(bad_char, '<STR_LIT:_>')<EOL><DEDENT>return path<EOL>
|
Converts bad path characters to '_'.
:param path: str path to fix
:return: str fixed path
|
f3940:m0
|
def to_unicode(s):
|
return s if six.PY3 else str(s, '<STR_LIT:utf-8>')<EOL>
|
Convert a command line string to utf8 unicode.
:param s: string to convert to unicode
:return: unicode string for argument
|
f3940:m1
|
def add_project_name_arg(arg_parser, required, help_text):
|
arg_parser.add_argument("<STR_LIT>", '<STR_LIT>',<EOL>metavar='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT>',<EOL>help=help_text,<EOL>required=required)<EOL>
|
Adds project_name parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str label displayed in usage
|
f3940:m2
|
def add_project_id_arg(arg_parser, required, help_text):
|
arg_parser.add_argument("<STR_LIT>", '<STR_LIT>',<EOL>metavar='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT>',<EOL>help=help_text,<EOL>required=required)<EOL>
|
Adds project_name parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str label displayed in usage
|
f3940:m3
|
def add_project_name_or_id_arg(arg_parser, required=True, help_text_suffix="<STR_LIT>"):
|
project_name_or_id = arg_parser.add_mutually_exclusive_group(required=required)<EOL>name_help_text = "<STR_LIT>".format(help_text_suffix)<EOL>add_project_name_arg(project_name_or_id, required=False, help_text=name_help_text)<EOL>id_help_text = "<STR_LIT>".format(help_text_suffix)<EOL>add_project_id_arg(project_name_or_id, required=False, help_text=id_help_text)<EOL>
|
Adds project name or project id argument. These two are mutually exclusive.
:param arg_parser:
:param required:
:param help_text:
:return:
|
f3940:m4
|
def _paths_must_exists(path):
|
path = to_unicode(path)<EOL>if not os.path.exists(path):<EOL><INDENT>raise argparse.ArgumentTypeError("<STR_LIT>".format(path))<EOL><DEDENT>return path<EOL>
|
Raises error if path doesn't exist.
:param path: str path to check
:return: str same path passed in
|
f3940:m5
|
def format_destination_path(path):
|
path = to_unicode(path)<EOL>return _path_has_ok_chars(path)<EOL>
|
Formats command line destination path.
:param path: str path to check
:return: str path
|
f3940:m6
|
def _path_has_ok_chars(path):
|
basename = os.path.basename(path)<EOL>if any([bad_char in basename for bad_char in INVALID_PATH_CHARS]):<EOL><INDENT>raise argparse.ArgumentTypeError("<STR_LIT>".format(path))<EOL><DEDENT>return path<EOL>
|
Validate path for invalid characters.
:param path: str possible filesystem path
:return: path if it was ok otherwise raises error
|
f3940:m7
|
def _add_folders_positional_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>",<EOL>type=_paths_must_exists)<EOL>
|
Adds folders and/or filenames parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m8
|
def _add_folder_positional_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>",<EOL>nargs='<STR_LIT:?>')<EOL>
|
Adds folders and/or filenames parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m9
|
def _add_follow_symlinks_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>')<EOL>
|
Adds optional follow_symlinks parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m10
|
def add_user_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT:username>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>
|
Adds username parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m11
|
def add_email_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT:email>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>
|
Adds user_email parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m12
|
def _add_auth_role_arg(arg_parser, default_permissions):
|
help_text = "<STR_LIT>"<EOL>help_text += "<STR_LIT>"<EOL>arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT>',<EOL>help=help_text,<EOL>default=default_permissions)<EOL>
|
Adds optional auth_role parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param default_permissions: default value to use for this argument
|
f3940:m15
|
def _add_project_filter_auth_role_arg(arg_parser):
|
help_text = "<STR_LIT>"<EOL>help_text += "<STR_LIT>"<EOL>arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT>',<EOL>help=help_text,<EOL>default=None)<EOL>
|
Adds optional auth_role filtering parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m16
|
def _add_copy_project_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>action='<STR_LIT:store_true>',<EOL>default=False,<EOL>dest='<STR_LIT>')<EOL>
|
Adds optional copy_project parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m17
|
def _add_resend_arg(arg_parser, resend_help):
|
arg_parser.add_argument("<STR_LIT>",<EOL>action='<STR_LIT:store_true>',<EOL>default=False,<EOL>dest='<STR_LIT>',<EOL>help=resend_help)<EOL>
|
Adds resend parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param type_str
|
f3940:m18
|
def _add_force_arg(arg_parser, help_text):
|
arg_parser.add_argument("<STR_LIT>",<EOL>help=help_text,<EOL>action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>')<EOL>
|
Adds optional force parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str label displayed in usage
|
f3940:m19
|
def _add_include_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>action='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT>',<EOL>help="<STR_LIT>",<EOL>default=[])<EOL>
|
Adds optional repeatable include parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m20
|
def _add_exclude_arg(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>action='<STR_LIT>',<EOL>type=to_unicode,<EOL>dest='<STR_LIT>',<EOL>help="<STR_LIT>",<EOL>default=[])<EOL>
|
Adds optional repeatable exclude parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m21
|
def _add_dry_run(arg_parser, help_text):
|
arg_parser.add_argument("<STR_LIT>",<EOL>help=help_text,<EOL>action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>')<EOL>
|
Adds optional --dry-run parameter to a parser. Stored as 'dry_run'.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str label displayed in usage
|
f3940:m22
|
def _skip_config_file_permission_check(arg_parser):
|
arg_parser.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>',<EOL>default=False)<EOL>
|
Adds optional follow_symlinks parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m23
|
def _add_message_file(arg_parser, help_text):
|
arg_parser.add_argument('<STR_LIT>',<EOL>type=argparse.FileType('<STR_LIT:r>'),<EOL>help=help_text)<EOL>
|
Add mesage file argument with help_text to arg_parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str: help text for this argument
|
f3940:m24
|
def _add_long_format_option(arg_parser, help_text):
|
arg_parser.add_argument("<STR_LIT>",<EOL>help=help_text,<EOL>action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>')<EOL>
|
Adds optional follow_symlinks parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
|
f3940:m25
|
def register_upload_command(self, upload_func):
|
description = "<STR_LIT>"<EOL>upload_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>_add_dry_run(upload_parser, help_text="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>add_project_name_or_id_arg(upload_parser, help_text_suffix="<STR_LIT>")<EOL>_add_folders_positional_arg(upload_parser)<EOL>_add_follow_symlinks_arg(upload_parser)<EOL>upload_parser.set_defaults(func=upload_func)<EOL>
|
Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks).
|
f3940:c0:m1
|
def register_add_user_command(self, add_user_func):
|
description = "<STR_LIT>"<EOL>add_user_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>add_project_name_or_id_arg(add_user_parser, help_text_suffix="<STR_LIT>")<EOL>user_or_email = add_user_parser.add_mutually_exclusive_group(required=True)<EOL>add_user_arg(user_or_email)<EOL>add_email_arg(user_or_email)<EOL>_add_auth_role_arg(add_user_parser, default_permissions='<STR_LIT>')<EOL>add_user_parser.set_defaults(func=add_user_func)<EOL>
|
Add the add-user command to the parser and call add_user_func(project_name, user_full_name, auth_role)
when chosen.
:param add_user_func: func Called when this option is chosen: upload_func(project_name, user_full_name, auth_role).
|
f3940:c0:m2
|
def register_remove_user_command(self, remove_user_func):
|
description = "<STR_LIT>"<EOL>remove_user_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>add_project_name_or_id_arg(remove_user_parser, help_text_suffix="<STR_LIT>")<EOL>user_or_email = remove_user_parser.add_mutually_exclusive_group(required=True)<EOL>add_user_arg(user_or_email)<EOL>add_email_arg(user_or_email)<EOL>remove_user_parser.set_defaults(func=remove_user_func)<EOL>
|
Add the remove-user command to the parser and call remove_user_func(project_name, user_full_name) when chosen.
:param remove_user_func: func Called when this option is chosen: remove_user_func(project_name, user_full_name).
|
f3940:c0:m3
|
def register_download_command(self, download_func):
|
description = "<STR_LIT>"<EOL>download_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>add_project_name_or_id_arg(download_parser, help_text_suffix="<STR_LIT>")<EOL>_add_folder_positional_arg(download_parser)<EOL>include_or_exclude = download_parser.add_mutually_exclusive_group(required=False)<EOL>_add_include_arg(include_or_exclude)<EOL>_add_exclude_arg(include_or_exclude)<EOL>download_parser.set_defaults(func=download_func)<EOL>
|
Add 'download' command for downloading a project to a directory.
For non empty directories it will download remote files replacing local files.
:param download_func: function to run when user choses this option
|
f3940:c0:m4
|
def register_share_command(self, share_func):
|
description = "<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>share_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>add_project_name_or_id_arg(share_parser)<EOL>user_or_email = share_parser.add_mutually_exclusive_group(required=True)<EOL>add_user_arg(user_or_email)<EOL>add_email_arg(user_or_email)<EOL>_add_auth_role_arg(share_parser, default_permissions='<STR_LIT>')<EOL>_add_resend_arg(share_parser, "<STR_LIT>")<EOL>_add_message_file(share_parser, "<STR_LIT>"<EOL>"<STR_LIT>")<EOL>share_parser.set_defaults(func=share_func)<EOL>
|
Add 'share' command for adding view only project permissions and sending email via another service.
:param share_func: function to run when user choses this option
|
f3940:c0:m5
|
def register_deliver_command(self, deliver_func):
|
description = "<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>deliver_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>add_project_name_or_id_arg(deliver_parser)<EOL>user_or_email = deliver_parser.add_mutually_exclusive_group(required=True)<EOL>add_user_arg(user_or_email)<EOL>add_email_arg(user_or_email)<EOL>add_share_usernames_arg(deliver_parser)<EOL>add_share_emails_arg(deliver_parser)<EOL>_add_copy_project_arg(deliver_parser)<EOL>_add_resend_arg(deliver_parser, "<STR_LIT>")<EOL>include_or_exclude = deliver_parser.add_mutually_exclusive_group(required=False)<EOL>_add_include_arg(include_or_exclude)<EOL>_add_exclude_arg(include_or_exclude)<EOL>_add_message_file(deliver_parser, "<STR_LIT>"<EOL>"<STR_LIT>")<EOL>deliver_parser.set_defaults(func=deliver_func)<EOL>
|
Add 'deliver' command for transferring a project to another user.,
:param deliver_func: function to run when user choses this option
|
f3940:c0:m6
|
def register_list_command(self, list_func):
|
description = "<STR_LIT>"<EOL>list_parser = self.subparsers.add_parser('<STR_LIT:list>', description=description)<EOL>project_name_or_auth_role = list_parser.add_mutually_exclusive_group(required=False)<EOL>_add_project_filter_auth_role_arg(project_name_or_auth_role)<EOL>add_project_name_or_id_arg(project_name_or_auth_role, required=False,<EOL>help_text_suffix="<STR_LIT>")<EOL>_add_long_format_option(list_parser, '<STR_LIT>')<EOL>list_parser.set_defaults(func=list_func)<EOL>
|
Add 'list' command to get a list of projects or details about one project.
:param list_func: function: run when user choses this option.
|
f3940:c0:m7
|
def register_delete_command(self, delete_func):
|
description = "<STR_LIT>"<EOL>delete_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>add_project_name_or_id_arg(delete_parser, help_text_suffix="<STR_LIT>")<EOL>_add_force_arg(delete_parser, "<STR_LIT>")<EOL>delete_parser.set_defaults(func=delete_func)<EOL>
|
Add 'delete' command delete a project from the remote store.
:param delete_func: function: run when user choses this option.
|
f3940:c0:m8
|
def register_list_auth_roles_command(self, list_auth_roles_func):
|
description = "<STR_LIT>"<EOL>list_auth_roles_parser = self.subparsers.add_parser('<STR_LIT>', description=description)<EOL>list_auth_roles_parser.set_defaults(func=list_auth_roles_func)<EOL>
|
Add 'list_auth_roles' command to list project authorization roles that can be used with add_user.
:param list_auth_roles_func: function: run when user choses this option.
|
f3940:c0:m9
|
def run_command(self, args):
|
parsed_args = self.parser.parse_args(args)<EOL>if hasattr(parsed_args, '<STR_LIT>'):<EOL><INDENT>parsed_args.func(parsed_args)<EOL><DEDENT>else:<EOL><INDENT>self.parser.print_help()<EOL><DEDENT>
|
Parse command line arguments and run function registered for the appropriate command.
:param args: [str] command line arguments
|
f3940:c0:m10
|
def loader(schema, validator=CerberusValidator, update=None):
|
if not issubclass(validator, CerberusValidator):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return partial(load, schema, validator, update)<EOL>
|
Create a load function based on schema dict and Validator class.
:param schema: a Cerberus schema dict.
:param validator: the validator class which must be a subclass of
more.cerberus.CerberusValidator which is the default.
:param update: will pass the update flag to the validator, when ``True``
the ``required`` rules will not be checked.
By default it will be set for PUT and PATCH requests to ``True``
and for other requests to ``False``.
You can plug this ``load`` function into a json view.
Returns a ``load`` function that takes a request JSON body
and uses the schema to validate it. This function raises
:class:`more.cerberus.ValidationError` if validation is not successful.
|
f3947:m1
|
@abstractproperty<EOL><INDENT>def name(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Give the name.
|
f3962:c0:m0
|
@abstractmethod<EOL><INDENT>def get_name(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Set the method that should give the name.
|
f3962:c0:m1
|
@abstractmethod<EOL><INDENT>def is_marmee(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Give if it is the implementation.
|
f3962:c0:m2
|
@abstractproperty<EOL><INDENT>def inputs(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Give the inputs of a calculation at certain point.
|
f3962:c0:m3
|
@abstractmethod<EOL><INDENT>def set_inputs(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Set the method that should place the inputs.
|
f3962:c0:m4
|
@abstractproperty<EOL><INDENT>def outputs(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Give the outputs of a calculation at certain point.
|
f3962:c0:m5
|
@abstractmethod<EOL><INDENT>def get_outputs(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Set the method that should give the outputs.
|
f3962:c0:m6
|
@abstractproperty<EOL><INDENT>def filters(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Give the filters of a calculation at certain point.
|
f3962:c0:m7
|
@abstractmethod<EOL><INDENT>def set_filters(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Set the method that should place the filters.
|
f3962:c0:m8
|
def parse(self):
|
if self.type == TOKEN_TYPE[<NUM_LIT:0>][<NUM_LIT:1>]:<EOL><INDENT>try:<EOL><INDENT>return Item(<EOL>item_id=self._link(None, None)[<NUM_LIT:1>],<EOL>links=self._link(None, None)[<NUM_LIT:0>],<EOL>assets=self._asset(None),<EOL>properties=self._properties(None)[<NUM_LIT:0>],<EOL>geometry=self._properties(None)[<NUM_LIT:2>]<EOL>)<EOL><DEDENT>except ValidationError as e:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>elif self.type == TOKEN_TYPE[<NUM_LIT:1>][<NUM_LIT:1>]:<EOL><INDENT>try:<EOL><INDENT>items = [self._features_iterator(<EOL>feature['<STR_LIT:id>'],<EOL>self._link(feature, data.ASSET_TYPE_IMAGE_COLL)[<NUM_LIT:0>],<EOL>self._asset(<EOL>feature['<STR_LIT>']['<STR_LIT>']<EOL>),<EOL>self._properties(feature)[<NUM_LIT:0>],<EOL>self._properties(feature)[<NUM_LIT:2>]<EOL>) for feature in self._get_full_info()['<STR_LIT>']]<EOL>res_list = dask.compute(items)[<NUM_LIT:0>]<EOL>return Collection(<EOL>collection_id=self._get_info()['<STR_LIT:id>'],<EOL>features=res_list<EOL>)<EOL><DEDENT>except ValidationError as e:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>
|
Parse an asset from Earth Engine to STAC item
Raises:
ValueError -- If asset is not of type Image or ImageCollection
Returns:
Item -- STAC feature of the Google Earth Engine Asset
Collection -- STAC collection of the Google Earth Engine Asset
|
f3963:c0:m2
|
def load_key(pubkey):
|
try:<EOL><INDENT>return load_pem_public_key(pubkey.encode(), default_backend())<EOL><DEDENT>except ValueError:<EOL><INDENT>pubkey = pubkey.replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>return load_pem_public_key(pubkey.encode(), default_backend())<EOL><DEDENT>
|
Load public RSA key.
Work around keys with incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
|
f3966:m0
|
def encrypt(pubkey, password):
|
key = load_key(pubkey)<EOL>encrypted_password = key.encrypt(password, PKCS1v15())<EOL>return base64.b64encode(encrypted_password)<EOL>
|
Encrypt password using given RSA public key and encode it with base64.
The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis).
|
f3966:m1
|
def fetch_public_key(repo):
|
keyurl = '<STR_LIT>'.format(repo)<EOL>data = json.loads(urlopen(keyurl).read().decode())<EOL>if '<STR_LIT:key>' not in data:<EOL><INDENT>errmsg = "<STR_LIT>".format(repo)<EOL>errmsg += "<STR_LIT>"<EOL>raise ValueError(errmsg)<EOL><DEDENT>return data['<STR_LIT:key>']<EOL>
|
Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
|
f3966:m2
|
def prepend_line(filepath, line):
|
with open(filepath) as f:<EOL><INDENT>lines = f.readlines()<EOL><DEDENT>lines.insert(<NUM_LIT:0>, line)<EOL>with open(filepath, '<STR_LIT:w>') as f:<EOL><INDENT>f.writelines(lines)<EOL><DEDENT>
|
Rewrite a file adding a line to its beginning.
|
f3966:m3
|
def load_yaml_config(filepath):
|
with open(filepath) as f:<EOL><INDENT>return yaml.load(f)<EOL><DEDENT>
|
Load yaml config file at the given path.
|
f3966:m4
|
def save_yaml_config(filepath, config):
|
with open(filepath, '<STR_LIT:w>') as f:<EOL><INDENT>yaml.dump(config, f, default_flow_style=False)<EOL><DEDENT>
|
Save yaml config file at the given path.
|
f3966:m5
|
def update_travis_deploy_password(encrypted_password):
|
config = load_yaml_config(TRAVIS_CONFIG_FILE)<EOL>config['<STR_LIT>']['<STR_LIT:password>'] = dict(secure=encrypted_password)<EOL>save_yaml_config(TRAVIS_CONFIG_FILE, config)<EOL>line = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>prepend_line(TRAVIS_CONFIG_FILE, line)<EOL>
|
Put `encrypted_password` into the deploy section of .travis.yml.
|
f3966:m6
|
def main(args):
|
public_key = fetch_public_key(args.repo)<EOL>password = args.password or getpass('<STR_LIT>')<EOL>update_travis_deploy_password(encrypt(public_key, password.encode()))<EOL>print("<STR_LIT>")<EOL>
|
Add a PyPI password to .travis.yml so that Travis can deploy to PyPI.
Fetch the Travis public key for the repo, and encrypt the PyPI password
with it before adding, so that only Travis can decrypt and use the PyPI
password.
|
f3966:m7
|
def config(env=DEFAULT_ENV, default=None, **overrides):
|
config = {}<EOL>s = os.environ.get(env, default)<EOL>if s:<EOL><INDENT>config = parse(s)<EOL><DEDENT>overrides = dict([(k.upper(), v) for k, v in overrides.items()])<EOL>config.update(overrides)<EOL>return config<EOL>
|
Returns configured REDIS dictionary from REDIS_URL.
|
f3969:m0
|
def parse(url):
|
config = {}<EOL>url = urlparse.urlparse(url)<EOL>path = url.path[<NUM_LIT:1>:]<EOL>path = path.split('<STR_LIT:?>', <NUM_LIT:2>)[<NUM_LIT:0>]<EOL>config.update({<EOL>"<STR_LIT>": int(path or <NUM_LIT:0>),<EOL>"<STR_LIT>": url.password or None,<EOL>"<STR_LIT>": url.hostname or "<STR_LIT:localhost>",<EOL>"<STR_LIT>": int(url.port or <NUM_LIT>),<EOL>})<EOL>return config<EOL>
|
Parses a database URL.
|
f3969:m1
|
def get_bytes(num_bytes):
|
<EOL>s = create_string_buffer(num_bytes)<EOL>ok = c_int()<EOL>hProv = c_ulong()<EOL>ok = windll.Advapi32.CryptAcquireContextA(byref(hProv), None, None, PROV_RSA_FULL, <NUM_LIT:0>)<EOL>ok = windll.Advapi32.CryptGenRandom(hProv, wintypes.DWORD(num_bytes), cast(byref(s), POINTER(c_byte)))<EOL>return s.raw<EOL>
|
Returns a random string of num_bytes length.
|
f3972:m0
|
def get_long():
|
<EOL>pbRandomData = c_ulong()<EOL>size_of_long = wintypes.DWORD(sizeof(pbRandomData))<EOL>ok = c_int()<EOL>hProv = c_ulong()<EOL>ok = windll.Advapi32.CryptAcquireContextA(byref(hProv), None, None, PROV_RSA_FULL, <NUM_LIT:0>)<EOL>ok = windll.Advapi32.CryptGenRandom(hProv, size_of_long, byref(pbRandomData))<EOL>return pbRandomData.value<EOL>
|
Generates a random long. The length of said long varies by platform.
|
f3972:m1
|
def capitalize(<EOL>full_name,<EOL>articles=None,<EOL>separator_characters=None,<EOL>ignore_worls=None,<EOL>):
|
if articles is None:<EOL><INDENT>articles = _ARTICLES<EOL><DEDENT>if separator_characters is None:<EOL><INDENT>separator_characters = _SEPARATOR_CHARACTERS<EOL><DEDENT>if ignore_worls is None:<EOL><INDENT>ignore_worls = _IGNORE_WORLS<EOL><DEDENT>new_full_name = full_name<EOL>if hasattr(new_full_name, '<STR_LIT>'):<EOL><INDENT>new_full_name = new_full_name.strip()<EOL><DEDENT>if not new_full_name:<EOL><INDENT>return full_name<EOL><DEDENT>new_full_name = deep_unicode(new_full_name)<EOL>list_full_name = []<EOL>start_idx = <NUM_LIT:0><EOL>for step_idx, char in enumerate(list(new_full_name)):<EOL><INDENT>if char in separator_characters:<EOL><INDENT>list_full_name.extend(<EOL>[<EOL>_setting_word(<EOL>new_full_name[start_idx:step_idx],<EOL>separator_characters, ignore_worls,<EOL>articles if list_full_name else []<EOL>),<EOL>char<EOL>]<EOL>)<EOL>start_idx = step_idx + <NUM_LIT:1><EOL><DEDENT><DEDENT>list_full_name.append(<EOL>_setting_word(<EOL>new_full_name[start_idx:],<EOL>separator_characters, ignore_worls, articles<EOL>)<EOL>)<EOL>return '<STR_LIT>'.join(list_full_name)<EOL>
|
Returns the correct writing of a compound name, respecting the
first letters of the names in upper case.
|
f3979:m0
|
def deep_unicode(s, encodings=None):
|
if encodings is None:<EOL><INDENT>encodings = ['<STR_LIT:utf-8>', '<STR_LIT>']<EOL><DEDENT>if isinstance(s, (list, tuple)):<EOL><INDENT>return [deep_unicode(i) for i in s]<EOL><DEDENT>if isinstance(s, dict):<EOL><INDENT>return dict([<EOL>(deep_unicode(key), deep_unicode(s[key]))<EOL>for key in s<EOL>])<EOL><DEDENT>elif isinstance(s, str):<EOL><INDENT>for encoding in encodings:<EOL><INDENT>try:<EOL><INDENT>return s.decode(encoding)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>return s<EOL>
|
decode "DEEP" S using the codec registered for encoding.
|
f3979:m2
|
def deep_encode(s, encoding='<STR_LIT:utf-8>', errors='<STR_LIT:strict>'):
|
<EOL>s = deep_encode(s)<EOL>if sys.version_info.major < <NUM_LIT:3> and isinstance(s, unicode):<EOL><INDENT>return s.encode(encoding, errors)<EOL><DEDENT>if isinstance(s, (list, tuple)):<EOL><INDENT>return [deep_encode(i, encoding=encoding, errors=errors) for i in s]<EOL><DEDENT>if isinstance(s, dict):<EOL><INDENT>return dict([<EOL>(<EOL>deep_encode(key, encoding=encoding, errors=errors),<EOL>deep_encode(s[key], encoding=encoding, errors=errors)<EOL>) for key in s<EOL>])<EOL><DEDENT>return s<EOL>
|
Encode "DEEP" S using the codec registered for encoding.
|
f3979:m3
|
def _check_valid_key(self, key):
|
if not isinstance(key, key_type) and key is not None:<EOL><INDENT>raise ValueError('<STR_LIT>' % key)<EOL><DEDENT>if not VALID_KEY_RE_EXTENDED.match(key) or key == u'<STR_LIT:/>':<EOL><INDENT>raise ValueError('<STR_LIT>' % key)<EOL><DEDENT>
|
Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked
|
f3981:c0:m0
|
def _on_tree(repo, tree, components, obj):
|
<EOL>if len(components) == <NUM_LIT:1>:<EOL><INDENT>if isinstance(obj, Blob):<EOL><INDENT>mode = <NUM_LIT><EOL><DEDENT>elif isinstance(obj, Tree):<EOL><INDENT>mode = <NUM_LIT><EOL><DEDENT>elif obj is None:<EOL><INDENT>mode = None<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>name = components[<NUM_LIT:0>]<EOL>if mode is not None:<EOL><INDENT>tree[name] = mode, obj.id<EOL>return [tree]<EOL><DEDENT>if name in tree:<EOL><INDENT>del tree[name]<EOL><DEDENT>return [tree]<EOL><DEDENT>elif len(components) > <NUM_LIT:1>:<EOL><INDENT>a, bc = components[<NUM_LIT:0>], components[<NUM_LIT:1>:]<EOL>if a in tree:<EOL><INDENT>a_tree = repo[tree[a][<NUM_LIT:1>]]<EOL>if not isinstance(a_tree, Tree):<EOL><INDENT>a_tree = Tree()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>a_tree = Tree()<EOL><DEDENT>res = _on_tree(repo, a_tree, bc, obj)<EOL>a_tree_new = res[-<NUM_LIT:1>]<EOL>if a_tree_new.items():<EOL><INDENT>tree[a] = <NUM_LIT>, a_tree_new.id<EOL>return res + [tree]<EOL><DEDENT>if a in tree:<EOL><INDENT>del tree[a]<EOL><DEDENT>return [tree]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>
|
Mounts an object on a tree, using the given path components.
:param tree: Tree object to mount on.
:param components: A list of strings of subpaths (i.e. ['foo', 'bar'] is
equivalent to '/foo/bar')
:param obj: Object to mount. If None, removes the object found at path
and prunes the tree downwards.
:return: A list of new entities that need to be added to the object store,
where the last one is the new tree.
|
f3982:m0
|
def delete(self, key):
|
self._dstore.delete(key)<EOL>self.cache.delete(key)<EOL>
|
Implementation of :meth:`~simplekv.KeyValueStore.delete`.
If an exception occurs in either the cache or backing store, all are
passing on.
|
f3984:c0:m1
|
def get(self, key):
|
try:<EOL><INDENT>return self.cache.get(key)<EOL><DEDENT>except KeyError:<EOL><INDENT>data = self._dstore.get(key)<EOL>self.cache.put(key, data)<EOL>return data<EOL><DEDENT>except IOError:<EOL><INDENT>return self._dstore.get(key)<EOL><DEDENT>
|
Implementation of :meth:`~simplekv.KeyValueStore.get`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the backing store is consulted directly.
It is possible for a caching error to occur while attempting to store
the value in the cache. It will not be handled as well.
|
f3984:c0:m2
|
def get_file(self, key, file):
|
try:<EOL><INDENT>return self.cache.get_file(key, file)<EOL><DEDENT>except KeyError:<EOL><INDENT>fp = self._dstore.open(key)<EOL>self.cache.put_file(key, fp)<EOL>return self.cache.get_file(key, file)<EOL><DEDENT>
|
Implementation of :meth:`~simplekv.KeyValueStore.get_file`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the retrieval cannot
proceed: If ``file`` was an open file, data maybe been written to it
already. The :exc:`~exceptions.IOError` bubbles up.
It is possible for a caching error to occur while attempting to store
the value in the cache. It will not be handled as well.
|
f3984:c0:m3
|
def open(self, key):
|
try:<EOL><INDENT>return self.cache.open(key)<EOL><DEDENT>except KeyError:<EOL><INDENT>fp = self._dstore.open(key)<EOL>self.cache.put_file(key, fp)<EOL>return self.cache.open(key)<EOL><DEDENT>except IOError:<EOL><INDENT>return self._dstore.open(key)<EOL><DEDENT>
|
Implementation of :meth:`~simplekv.KeyValueStore.open`.
If a cache miss occurs, the value is retrieved, stored in the cache,
then then another open is issued on the cache.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the backing store is consulted directly.
It is possible for a caching error to occur while attempting to store
the value in the cache. It will not be handled as well.
|
f3984:c0:m4
|
def copy(self, source, dest):
|
try:<EOL><INDENT>k = self._dstore.copy(source, dest)<EOL><DEDENT>finally:<EOL><INDENT>self.cache.delete(dest)<EOL><DEDENT>return k<EOL>
|
Implementation of :meth:`~simplekv.CopyMixin.copy`.
Copies the data in the backing store and removes the destination key from the cache,
in case it was already populated.
Does not work when the backing store does not implement copy.
|
f3984:c0:m5
|
def put(self, key, data):
|
try:<EOL><INDENT>return self._dstore.put(key, data)<EOL><DEDENT>finally:<EOL><INDENT>self.cache.delete(key)<EOL><DEDENT>
|
Implementation of :meth:`~simplekv.KeyValueStore.put`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
|
f3984:c0:m6
|
def put_file(self, key, file):
|
try:<EOL><INDENT>return self._dstore.put_file(key, file)<EOL><DEDENT>finally:<EOL><INDENT>self.cache.delete(key)<EOL><DEDENT>
|
Implementation of :meth:`~simplekv.KeyValueStore.put_file`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
|
f3984:c0:m7
|
def keys(self, prefix=u"<STR_LIT>"):
|
return list(self.iter_keys(prefix))<EOL>
|
Return a list of keys currently in store, in any order
:raises IOError: If there was an error accessing the store.
|
f3985:c1:m10
|
def lazy_property(fn):
|
attr_name = '<STR_LIT>' + fn.__name__<EOL>@property<EOL>def _lazy_property(self):<EOL><INDENT>if not hasattr(self, attr_name):<EOL><INDENT>setattr(self, attr_name, fn(self))<EOL><DEDENT>return getattr(self, attr_name)<EOL><DEDENT>return _lazy_property<EOL>
|
Decorator that makes a property lazy-evaluated.
|
f3988:m0
|
def _file_md5(file_):
|
md5 = hashlib.md5()<EOL>chunk_size = <NUM_LIT> * md5.block_size<EOL>for chunk in iter(lambda: file_.read(chunk_size), b'<STR_LIT>'):<EOL><INDENT>md5.update(chunk)<EOL><DEDENT>file_.seek(<NUM_LIT:0>)<EOL>byte_digest = md5.digest()<EOL>return base64.b64encode(byte_digest).decode()<EOL>
|
Compute the md5 digest of a file in base64 encoding.
|
f3988:m1
|
def _filename_md5(filename):
|
with open(filename, '<STR_LIT:rb>') as f:<EOL><INDENT>return _file_md5(f)<EOL><DEDENT>
|
Compute the md5 digest of a file in base64 encoding.
|
f3988:m2
|
def _byte_buffer_md5(buffer_):
|
md5 = hashlib.md5(buffer_)<EOL>byte_digest = md5.digest()<EOL>return base64.b64encode(byte_digest).decode()<EOL>
|
Computes the md5 digest of a byte buffer in base64 encoding.
|
f3988:m3
|
@contextmanager<EOL>def map_azure_exceptions(key=None, exc_pass=()):
|
from azure.common import AzureMissingResourceHttpError, AzureHttpError,AzureException<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>except AzureMissingResourceHttpError as ex:<EOL><INDENT>if ex.__class__.__name__ not in exc_pass:<EOL><INDENT>s = str(ex)<EOL>if s.startswith(u"<STR_LIT>"):<EOL><INDENT>raise IOError(s)<EOL><DEDENT>raise KeyError(key)<EOL><DEDENT><DEDENT>except AzureHttpError as ex:<EOL><INDENT>if ex.__class__.__name__ not in exc_pass:<EOL><INDENT>raise IOError(str(ex))<EOL><DEDENT><DEDENT>except AzureException as ex:<EOL><INDENT>if ex.__class__.__name__ not in exc_pass:<EOL><INDENT>raise IOError(str(ex))<EOL><DEDENT><DEDENT>
|
Map Azure-specific exceptions to the simplekv-API.
|
f3988:m4
|
def tell(self):
|
if self.closed:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return self.pos<EOL>
|
Returns he current offset as int. Always >= 0.
|
f3988:c1:m1
|
def read(self, size=-<NUM_LIT:1>):
|
if self.closed:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>with map_azure_exceptions(key=self.key):<EOL><INDENT>if size < <NUM_LIT:0>:<EOL><INDENT>size = self.size - self.pos<EOL><DEDENT>end = min(self.pos + size - <NUM_LIT:1>, self.size - <NUM_LIT:1>)<EOL>if self.pos > end:<EOL><INDENT>return b'<STR_LIT>'<EOL><DEDENT>b = self.block_blob_service.get_blob_to_bytes(<EOL>container_name=self.container_name,<EOL>blob_name=self.key,<EOL>start_range=self.pos,<EOL>end_range=end, <EOL>max_connections=self.max_connections,<EOL>)<EOL>self.pos += len(b.content)<EOL>return b.content<EOL><DEDENT>
|
Returns 'size' amount of bytes or less if there is no more data.
If no size is given all data is returned. size can be >= 0.
|
f3988:c1:m2
|
def seek(self, offset, whence=<NUM_LIT:0>):
|
if self.closed:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if whence == <NUM_LIT:0>:<EOL><INDENT>if offset < <NUM_LIT:0>:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>self.pos = offset<EOL><DEDENT>elif whence == <NUM_LIT:1>:<EOL><INDENT>if self.pos + offset < <NUM_LIT:0>:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>self.pos += offset<EOL><DEDENT>elif whence == <NUM_LIT:2>:<EOL><INDENT>if self.size + offset < <NUM_LIT:0>:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>self.pos = self.size + offset<EOL><DEDENT>return self.pos<EOL>
|
Move to a new offset either relative or absolute. whence=0 is
absolute, whence=1 is relative, whence=2 is relative to the end.
Any relative or absolute seek operation which would result in a
negative position is undefined and that case can be ignored
in the implementation.
Any seek operation which moves the position after the stream
should succeed. tell() should report that position and read()
should return an empty bytes object.
|
f3988:c1:m3
|
@contextmanager<EOL>def map_boto_exceptions(key=None, exc_pass=()):
|
from boto.exception import BotoClientError, BotoServerError,StorageResponseError<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>except StorageResponseError as e:<EOL><INDENT>if e.code == '<STR_LIT>':<EOL><INDENT>raise KeyError(key)<EOL><DEDENT>raise IOError(str(e))<EOL><DEDENT>except (BotoClientError, BotoServerError) as e:<EOL><INDENT>if e.__class__.__name__ not in exc_pass:<EOL><INDENT>raise IOError(str(e))<EOL><DEDENT><DEDENT>
|
Map boto-specific exceptions to the simplekv-API.
|
f3989:m0
|
def __upload_args(self):
|
d = {<EOL>'<STR_LIT>': self.reduced_redundancy,<EOL>}<EOL>if self.public:<EOL><INDENT>d['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>return d<EOL>
|
Generates a dictionary of arguments to pass to various
set_content_from* functions. This allows us to save API calls by
passing the necessary parameters on with the upload.
|
f3989:c0:m2
|
def __contains__(self, key):
|
self._check_valid_key(key)<EOL>return self._has_key(key)<EOL>
|
Checks if a key is present
:param key: The key whose existence should be verified.
:raises exceptions.ValueError: If the key is not valid.
:raises exceptions.IOError: If there was an error accessing the store.
:returns: True if the key exists, False otherwise.
|
f3993:c0:m0
|
def __iter__(self):
|
return self.iter_keys()<EOL>
|
Iterate over keys
:raises exceptions.IOError: If there was an error accessing the store.
|
f3993:c0:m1
|
def delete(self, key):
|
self._check_valid_key(key)<EOL>return self._delete(key)<EOL>
|
Delete key and data associated with it.
If the key does not exist, no error is reported.
:raises exceptions.ValueError: If the key is not valid.
:raises exceptions.IOError: If there was an error deleting.
|
f3993:c0:m2
|
def get(self, key):
|
self._check_valid_key(key)<EOL>return self._get(key)<EOL>
|
Returns the key data as a bytestring.
:param key: Value associated with the key, as a `bytes` object
:raises exceptions.ValueError: If the key is not valid.
:raises exceptions.IOError: If the file could not be read.
:raises exceptions.KeyError: If the key was not found.
|
f3993:c0:m3
|
def get_file(self, key, file):
|
self._check_valid_key(key)<EOL>if isinstance(file, str):<EOL><INDENT>return self._get_filename(key, file)<EOL><DEDENT>else:<EOL><INDENT>return self._get_file(key, file)<EOL><DEDENT>
|
Write contents of key to file
Like :meth:`.KeyValueStore.put_file`, this method allows backends to
implement a specialized function if data needs to be written to disk or
streamed.
If *file* is a string, contents of *key* are written to a newly
created file with the filename *file*. Otherwise, the data will be
written using the *write* method of *file*.
:param key: The key to be read
:param file: Output filename or an object with a *write* method.
:raises exceptions.ValueError: If the key is not valid.
:raises exceptions.IOError: If there was a problem reading or writing
data.
:raises exceptions.KeyError: If the key was not found.
|
f3993:c0:m4
|
def iter_keys(self, prefix=u"<STR_LIT>"):
|
raise NotImplementedError<EOL>
|
Return an Iterator over all keys currently in the store, in any
order.
If prefix is not the empty string, iterates only over all keys starting with prefix.
:raises exceptions.IOError: If there was an error accessing the store.
|
f3993:c0:m5
|
def keys(self, prefix=u"<STR_LIT>"):
|
return list(self.iter_keys(prefix))<EOL>
|
Return a list of keys currently in store, in any order
If prefix is not the empty string, returns only all keys starting with prefix.
:raises exceptions.IOError: If there was an error accessing the store.
|
f3993:c0:m6
|
def open(self, key):
|
self._check_valid_key(key)<EOL>return self._open(key)<EOL>
|
Open key for reading.
Returns a read-only file-like object for reading a key.
:param key: Key to open
:raises exceptions.ValueError: If the key is not valid.
:raises exceptions.IOError: If the file could not be read.
:raises exceptions.KeyError: If the key was not found.
|
f3993:c0:m7
|
def put(self, key, data):
|
self._check_valid_key(key)<EOL>if not isinstance(data, bytes):<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>return self._put(key, data)<EOL>
|
Store into key from file
Stores bytestring *data* in *key*.
:param key: The key under which the data is to be stored
:param data: Data to be stored into key, must be `bytes`.
:returns: The key under which data was stored
:raises exceptions.ValueError: If the key is not valid.
:raises exceptions.IOError: If storing failed or the file could not
be read
|
f3993:c0:m8
|
def put_file(self, key, file):
|
<EOL>if isinstance(file, str):<EOL><INDENT>return self._put_filename(key, file)<EOL><DEDENT>else:<EOL><INDENT>return self._put_file(key, file)<EOL><DEDENT>
|
Store into key from file on disk
Stores data from a source into key. *file* can either be a string,
which will be interpretet as a filename, or an object with a *read()*
method.
If the passed object has a *fileno()* method, it may be used to speed
up the operation.
The file specified by *file*, if it is a filename, may be removed in
the process, to avoid copying if possible. If you need to make a copy,
pass the opened file instead.
:param key: The key under which the data is to be stored
:param file: A filename or an object with a read method. If a filename,
may be removed
:returns: The key under which data was stored
:raises exceptions.ValueError: If the key is not valid.
:raises exceptions.IOError: If there was a problem moving the file in.
|
f3993:c0:m9
|
def _check_valid_key(self, key):
|
if not isinstance(key, key_type):<EOL><INDENT>raise ValueError('<STR_LIT>' % key)<EOL><DEDENT>if not VALID_KEY_RE.match(key):<EOL><INDENT>raise ValueError('<STR_LIT>' % key)<EOL><DEDENT>
|
Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked
|
f3993:c0:m10
|
def _delete(self, key):
|
raise NotImplementedError<EOL>
|
Implementation for :meth:`~simplekv.KeyValueStore.delete`. The
default implementation will simply raise a
:py:exc:`~exceptions.NotImplementedError`.
|
f3993:c0:m11
|
def _get(self, key):
|
buf = BytesIO()<EOL>self._get_file(key, buf)<EOL>return buf.getvalue()<EOL>
|
Implementation for :meth:`~simplekv.KeyValueStore.get`. The default
implementation will create a :class:`io.BytesIO`-buffer and then call
:meth:`~simplekv.KeyValueStore._get_file`.
:param key: Key of value to be retrieved
|
f3993:c0:m12
|
def _get_file(self, key, file):
|
bufsize = <NUM_LIT> * <NUM_LIT><EOL>source = self.open(key)<EOL>try:<EOL><INDENT>while True:<EOL><INDENT>buf = source.read(bufsize)<EOL>file.write(buf)<EOL>if len(buf) < bufsize:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>source.close()<EOL><DEDENT>
|
Write key to file-like object file. Either this method or
:meth:`~simplekv.KeyValueStore._get_filename` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. Note that this method does
not accept strings.
:param key: Key to be retrieved
:param file: File-like object to write to
|
f3993:c0:m13
|
def _get_filename(self, key, filename):
|
with open(filename, '<STR_LIT:wb>') as dest:<EOL><INDENT>return self._get_file(key, dest)<EOL><DEDENT>
|
Write key to file. Either this method or
:meth:`~simplekv.KeyValueStore._get_file` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. This method only accepts
filenames and will open the file with a mode of ``wb``, then call
:meth:`~simplekv.KeyValueStore._get_file`.
:param key: Key to be retrieved
:param filename: Filename to write to
|
f3993:c0:m14
|
def _has_key(self, key):
|
return key in self.keys()<EOL>
|
Default implementation for
:meth:`~simplekv.KeyValueStore.__contains__`.
Determines whether or not a key exists by calling
:meth:`~simplekv.KeyValueStore.keys`.
:param key: Key to check existance of
|
f3993:c0:m15
|
def _open(self, key):
|
raise NotImplementedError<EOL>
|
Open key for reading. Default implementation simply raises a
:py:exc:`~exceptions.NotImplementedError`.
:param key: Key to open
|
f3993:c0:m16
|
def _put(self, key, data):
|
return self._put_file(key, BytesIO(data))<EOL>
|
Implementation for :meth:`~simplekv.KeyValueStore.put`. The default
implementation will create a :class:`io.BytesIO`-buffer and then call
:meth:`~simplekv.KeyValueStore._put_file`.
:param key: Key under which data should be stored
:param data: Data to be stored
|
f3993:c0:m17
|
def _put_file(self, key, file):
|
raise NotImplementedError<EOL>
|
Store data from file-like object in key. Either this method or
:meth:`~simplekv.KeyValueStore._put_filename` will be called by
:meth:`~simplekv.KeyValueStore.put_file`. Note that this method does
not accept strings.
The default implementation will simply raise a
:py:exc:`~exceptions.NotImplementedError`.
:param key: Key under which data should be stored
:param file: File-like object to store data from
|
f3993:c0:m18
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.