text stringlengths 18 773k |
|---|
def _get_time(header, keys, name):
"""
Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch
"""
for key i... |
def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
... |
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.put_object(Body=b'', **client_kwarg... |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.delete_object(**client_kwargs)
... |
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_client_error():
response = self.client.list_buckets()
for bucket in response['Buckets']:
yield bucket.po... |
def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
... |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
# Get o... |
def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_client_error():
self._client.put_object(
Body=buffer.tobytes(), **self._client_kwargs) |
def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multi-part upload
if 'UploadId' not in self._upload_args:
with _handle_client_error():
self._upload_args[
'UploadId'] = self._client.create_multipart_uplo... |
def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
for part in self._write_futures:
part['ETag'] = part.pop('response').result()['ETag']
# Complete multipart upload
with _handle_client_error():
... |
def _handle_azure_exception():
"""
Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _AzureHttpError as exception:
if exception.status_code in _ERROR_CODES:
raise _ERROR_CODES[exception.sta... |
def _properties_model_to_dict(properties):
"""
Convert properties model to dict.
Args:
properties: Properties model.
Returns:
dict: Converted model.
"""
result = {}
for attr in properties.__dict__:
value = getattr(properties, attr)
if hasattr(value, '__modu... |
def _get_endpoint(self, sub_domain):
"""
Get endpoint information from storage parameters.
Update system with endpoint information and return information required
to define roots.
Args:
self (pycosio._core.io_system.SystemBase subclass): System.
sub_doma... |
def _secured_storage_parameters(self):
"""
Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters.
"""
parameters = self._storage_parameters or dict()
# Handles unsecure mode
if self._unsecure:
parameters... |
def _format_src_url(self, path, caller_system):
"""
Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
... |
def _update_listing_client_kwargs(client_kwargs, max_request_entries):
"""
Updates client kwargs for listing functions.
Args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Re... |
def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
... |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
stream ... |
def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
stream = _BytesIO()
with _handle_azure_exception():
self._get_to_stream(stream=stream, **self._client_kwargs)
return stream... |
def _init_append(self):
"""
Initializes file on 'a' mode.
"""
if self._content_length:
# Adjust size if content length specified
with _handle_azure_exception():
self._resize(
content_length=self._content_length, **self._client_k... |
def _create(self):
"""
Create the file if not exists.
"""
# Create new file
with _handle_azure_exception():
self._create_from_size(
content_length=self._content_length, **self._client_kwargs) |
def _flush(self, buffer, start, end):
"""
Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer p... |
def memoizedmethod(method):
"""
Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses.
"""... |
def _generate_async(self, generator):
"""
Return the previous generator object after having run the first element
evaluation as a background task.
Args:
generator (iterable): A generator function.
Returns:
iterable: The generator function with first elem... |
def _handle_client_exception():
"""
Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientException as exception:
if exception.http_status in _ERROR_CODES:
raise _ERROR_CODES[exceptio... |
def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
container, obj = self.split_locator... |
def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
container, obj = self.split_locator(path)
kwargs = dict(conta... |
def _get_client(self):
"""
Swift client
Returns:
swiftclient.client.Connection: client
"""
kwargs = self._storage_parameters
# Handles unsecure mode
if self._unsecure:
kwargs = kwargs.copy()
kwargs['ssl_compression'] = False
... |
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
... |
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.put_object(
... |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.delete_object(
... |
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_client_exception():
response = self.client.get_account()
for container in response[1]:
yield container.p... |
def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
... |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
try:
... |
def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
container, obj = self._client_args
with _handle_client_exception():
self._client.put_object(container, obj, buffer) |
def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Upload segment with workers
name = self._segment_name % self._seek
response = self._workers.submit(
self._client.put_object, self._container, name,
self._get_buffer())
# Sa... |
def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait segments upload completion
for segment in self._write_futures:
segment['etag'] = segment['etag'].result()
# Upload manifest file
with _handle_client_exception():
sel... |
def _init_append(self):
"""
Initializes file on 'a' mode.
"""
# Require to load the full file content in buffer
self._write_buffer[:] = self._readall()
# Make initial seek position to current end of file
self._seek = self._size |
def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._is_raw_of_buffered and not self._closed:
self._closed = True
if self._write_buffer:
self.flush() |
def _peek(self, size=-1):
"""
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
"""
with self._seek_lock:
see... |
def readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
# Get data starting from seek
... |
def readinto(self, b):
"""
Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read
"""
if not self._readable:
... |
def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
... |
def _update_seek(self, offset, whence):
"""
Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position.
"""
with self._seek_lock:
if whence == SEEK_SET:
self._seek = of... |
def write(self, b):
"""
Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written.
"""
if not self._w... |
def _handle_http_errors(response):
"""
Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response
"""
code = response.status_code
if 200 <= code < 400:
return response
elif code in (403, 404)... |
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
return _handle_http_errors(
self.client.request(
'HEAD', timeout=self._TIMEO... |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
# Get o... |
def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
return _handle_http_errors(
self._client.request(
'GET', self.name, timeout=self._TIMEOUT)).content |
def flush(self):
"""
Flush the write buffers of the stream if applicable and
save the object on the cloud.
"""
if self._writable:
with self._seek_lock:
buffer = self._get_buffer()
# Flush that part of the file
end = sel... |
def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
... |
def _flush(self):
"""
Flush the write buffers of the stream if applicable.
In write mode, send the buffer content to the cloud object.
"""
# Flush buffer to specified range
buffer = self._get_buffer()
start = self._buffer_size * (self._seek - 1)
end = sta... |
def _update_size(self, size, future):
"""
Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random... |
def _flush_range(self, buffer, start, end):
"""
Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buf... |
def _page(q, chunk=1000):
""" Quick utility to page a query, 1000 items at a time.
We need this so we don't OOM (out of memory) ourselves loading the world.
"""
offset = 0
while True:
r = False
for elem in q.limit(chunk).offset(offset):
r = True
yield elem
... |
def upgrade():
""" This takes a *really* long time. Like, hours. """
config_paths = context.config.get_main_option('fedmsg_config_dir')
filenames = fedmsg.config._gather_configs_in(config_paths)
config = fedmsg.config.load_config(filenames=filenames)
make_processors(**config)
engine = op.ge... |
def run(cmd):
""" Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use.
"""
status, output = commands.getstatusoutput(cmd)
if status:
print(output)
return status == 0 |
def read_datanommer_entries_from_filedump():
""" Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json
"""
# TODO -- un-hardcode this filename when I need to run this next time.
#filename = "../myfile.json"
filename = "../datanommer-dump-2012-11-22.json"
... |
def create_or_update(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Tuple[object, bool]:
"""
Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
... |
def maybe_convert_values(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Dict[str, Any]:
"""
Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upo... |
def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio.storage.azure._AzureBaseSystem subclass):
The source storage system.
"""
... |
def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
# Remove query string from URL
path = path.split('?', 1)[0]
... |
def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs... |
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_azure_exception():
for share in self.client.list_shares():
yield share.name, self._model_to_dict(share) |
def _list_objects(self, client_kwargs, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: o... |
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# Directory
if 'directory_name' in client_kwargs:
return self.client.create_directory(
... |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
return self.client.delete_file(
... |
def _update_range(self, data, **kwargs):
"""
Update range with data
Args:
data (bytes): data.
"""
self._client.update_range(data=data, **kwargs) |
def handle_bodhi(msg):
""" Given a bodhi message, return the FAS username. """
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submitter']
else:
username = msg.msg.get('... |
def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username |
def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
R... |
def format_and_is_storage(path):
"""
Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is ... |
def equivalent_to(std_function):
"""
Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function
"""
... |
def _handle_oss_error():
"""
Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _OssError as exception:
if exception.status in _ERROR_CODES:
raise _ERROR_CODES[exception.status](
... |
def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
copy_source = self.get_client_kwarg... |
def _get_client(self):
"""
OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client
"""
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss.Auth if self._storage_parameters
else _oss.AnonymousAuth)(**self.... |
def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
return (
# OSS Scheme
# - oss://<bucket>/<key>
'oss://',
# URL (With common aliyuncs.com endpoint):
... |
def _get_bucket(self, client_kwargs):
"""
Get bucket object.
Returns:
oss2.Bucket
"""
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_name']) |
def islink(self, path=None, header=None):
"""
Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink.
"""
if header is None:
he... |
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
... |
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
ret... |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
retur... |
def _model_to_dict(model, ignore):
"""
Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version.
"""
return {attr: value for attr, ... |
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_oss_error():
response = _oss.Service(
self.client, endpoint=self._endpoint).list_buckets()
for bucke... |
def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
... |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
if star... |
def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
with _handle_oss_error():
return self._bucket.get_object(key=self._key).read() |
def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_oss_error():
self._bucket.put_object(key=self._key, data=buffer.tobytes()) |
def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multipart upload
if self._upload_id is None:
with _handle_oss_error():
self._upload_id = self._bucket.init_multipart_upload(
self._key).upload_id
... |
def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
parts = [_PartInfo(part_number=future['part_number'],
etag=future['response'].result().etag)
for future in self._write_futures]
#... |
def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs):
"""
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opene... |
def _text_io_wrapper(stream, mode, encoding, errors, newline):
"""Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal ... |
def random_model(ctx, model_class_name):
"""
Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
... |
def random_models(ctx, model_class_name, min_count=0, max_count=3):
"""
Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
... |
def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only fi... |
def hash_key(self, key):
""" "Hash" all keys in a timerange to the same value. """
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key |
def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object]:
"""
Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
paramete... |
def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]):
"""
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances.
"""
if not identifiers:
return identifiers
def _create_o... |
def _load_data(self):
"""
Load all fixtures from :attr:`fixtures_dir`
"""
filenames = []
model_identifiers = defaultdict(list)
# attempt to load fixture files from given directories (first pass)
# for each valid model fixture file, read it into the cache and get ... |
def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]):
"""
Load fixtures from the given filename
"""
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
model_identifiers=model_identifiers)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.